RT 球球大佬们帮忙看看是哪里出了问题
----上传
/**
*
*接受前端上传的文件并存储至 MongoDB
* @
param file 前端上传的文件
* @
return 处理结果信息
*/
@
CrossOrigin @
ResponseBody @
RequestMapping(value = "/upload", method =
RequestMethod.POST)
public ReturnInfo fileUpload(@RequestParam MultipartFile file) throws Exception {
ReturnInfo<Map> info = new ReturnInfo<>();
if (!file.isEmpty()) {
BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());
String fileId = fileService.fileUpload(inputStream);
info.setCode(ReturnInfo.OK);
info.setMessage("上传成功!");
Map<String, String> resultMap = new HashMap<>();
resultMap.put("fileId", fileId);
info.setData(resultMap);
return info;
} else {
info.setMessage("文件不能为空");
info.setCode(ReturnInfo.ERROR);
return info;
}
}
/**
* 文件上传 service
*
* @
param fileInput 文件输入流
* @
return mongodb 对应文件 id
*/
@
Override public String fileUpload(InputStream fileInput) throws RestServiceException {
String fileType = FileUtil.getFileType(fileInput);
System.out.println(fileType);
//文件类型判断
if (!FileUtil.ENABLE_TYPES.contains(fileType)) {
throw new RestServiceException("不支持的文件类型!");
}
GridFSFile uploadFile = gridFsTemplate.store(fileInput, StringUtil.getUUID(), fileType);
return uploadFile.getId().toString();
}
----下载
/**下载请求
* 下载文件
*
* @
param fileId 文件 ID
* @
return */
@
CrossOrigin @
RequestMapping(value = "/download2/{fileId}", method = RequestMethod.GET)
@
ResponseBody public ResponseEntity<InputStreamResource> fileDownload2(@PathVariable String fileId) throws Exception {
//从 MongoDB 获取文件
GridFSDBFile file = fileService.getFileById(fileId);
String fileType = file.getContentType();
//设置文件 ContentType
MediaType mediaType = FileUtil.getEnableStr(fileType);
InputStreamResource resource = new InputStreamResource(file.getInputStream());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
headers.setContentDispositionFormData("attachment",file.getFilename()+"."+fileType);
//返回前端
return new ResponseEntity<>(resource, headers, HttpStatus.OK);
}
/**
*下载 service
*/
@
Override public GridFSDBFile getFileById(String fileId) throws RestServiceException {
GridFSDBFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(fileId)));
if (file == null) {
throw new RestServiceException("找不到相关文件!请检查 fileId");
}
return file;
}
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
https://www.v2ex.com/t/532360
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.