springboot上传下载文件
在yml配置相关内容
spring: #404 mvc: throw-exception-if-no-handler-found: true #静态资源 static-path-pattern: /** resources: #静态资源 static-locations: file:${img.location}
在我们配置404异常添加的配置要关掉(也就是说想用静态资源,就要放弃404异常的统一捕获,解决方案有:http://blog.springcloud.cn/sc/wk2/)
spring: #404 mvc: throw-exception-if-no-handler-found: true resources: add-mappings: false
上传文件:
前端:
<form enctype="multipart/form-data" id="uploadForm"> <input type="file" name="uploadFile" id="upload_file" style="margin-bottom:10px;"> <input type="button" id="uploadPicButton" value="上传" onclick="uploadImage()"> </form> var pic = $('#upload_file')[0].files[0]; var fd = new FormData(); var data = { header:{ token:"1212", reqOrg:"1212" }, body :{ spaceClassId:1 } } //fd.append('uploadFile', pic); fd.append('file', pic); fd.append('data', JSON.stringify(data)); //这里维持着是restful的形式 $.ajax({ url:'/resources/insertResources', type:"post", // Form数据 data: fd, cache: false, contentType: false, //不能用json了 processData: false, success:function(data){ console.log("ddd") } });
后端(用@RequestParam("file")接受参数,不能用@RequestBoby接受字符穿,我的方案是传@RequestParam然后自己来转bean
@PostMapping("/insertResources") @ResponseBody public SuccessResponse<Object> insertResources(@RequestParam("file") MultipartFile file, @RequestParam("data") String dataRequest) { DataRequest<SpaceClassHomework> spacePicDataRequest = JSON.parseObject(dataRequest, new TypeReference<DataRequest<SpaceClassHomework>>() { }); resourcesService.insertResources(file, spacePicDataRequest.getBody()); return new SuccessResponse<Object>(null); }
服务端 新的方法
file.transferTo(dest);
@Override public void insertResources(MultipartFile file, SpaceClassHomework spaceClassHomework) { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); String filePath = uploadDir; File dest = new File(filePath + fileName); try { file.transferTo(dest); } catch (IOException e) { e.printStackTrace(); log.error("文件上传失败"); } spaceClassHomework.setSpaceClassFileName(fileName); spaceClassHomework.setSpaceClassFilePath(filePath); spaceClassHomeworkMapper.insertSelective(spaceClassHomework); }
下载
前端:影响不大
后端:
1,不能和平时一样,加@responseBody
2,浏览器输出名字的时候编码不是utf-8,但是java又是utf-8,所有我用
String fileNameTemp = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
设置两个变量,一个浏览器输出,一个在java操作
3,spring方法,
new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
@GetMapping("/getResources") public ResponseEntity<byte[]> getSpaceClass(@RequestParam("spaceClassFileId") String spaceClassFileId , HttpServletResponse resp) throws Exception { String filePath = uploadDir; //获得路径和文件名 String fileName = resourcesService.getResources(Long.parseLong(spaceClassFileId)); String fileNameTemp = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", fileNameTemp); File file = new File(filePath + fileName); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);