版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36688143/article/details/84166676
需要注意的地方:
1)如果你复制我的代码到你的程序上报错,可以看看我第一篇文章实体类跟配置文件的设置:https://blog.csdn.net/qq_36688143/article/details/84162924
第二篇文件上传前端页面的代码:
https://blog.csdn.net/qq_36688143/article/details/84164885
2)提供两种方式转换文件信息以json字符串形式保存到数据库,Gson和org.json,转换代码在我的另一篇介绍各种Json的博客里有写:https://blog.csdn.net/qq_36688143/article/details/84135660
3)fastDFS负责上传下载的server设置
@Autowired
private FastDFSTemplate fastDFSTemplate;
4) 方法头中接收文件参数的设置
@RequestParam("uploadFile") CommonsMultipartFile[] files
// 二选一
MultipartFile[] files
5)判断文件是否非空
for(MultipartFile file:files) {
if (StringUtils.isNotBlank(file.getOriginalFilename())){}
}
6)上传的主要方法
// 文件上传,参数为文件byte,文件后缀
FastDfsInfo fastDfsInfo = fastDFSTemplate.upload(file.getBytes(), ext);
// 转换文件到界面显示类
FileInfo fileInfo = new FileInfo(file.getOriginalFilename(), ext, fastDfsInfo);
完整代码
@RequestMapping(value = "save")
public String save(@RequestParam("uploadFile") CommonsMultipartFile[] files, HttpServletRequest request, HttpServletResponse response) {
Gson gs = new Gson();
List<FileInfo> fileInfos = new ArrayList<FileInfo>();
for(MultipartFile file:files) {
// 如果选择了上传文件
if (StringUtils.isNotBlank(file.getOriginalFilename())){
long sizeL = file.getSize();
String size = FileInfo.getPrintSize(sizeL);
String ext = file.getOriginalFilename().split("\\.")[1];
String name = file.getOriginalFilename().split("\\.")[0];
try {
// 文件上传,参数为文件byte,文件后缀
FastDfsInfo fastDfsInfo = fastDFSTemplate.upload(file.getBytes(), ext);
// 转换文件到界面显示类
FileInfo fileInfo = new FileInfo(file.getOriginalFilename(), ext, fastDfsInfo);
fileInfo.setTitle(name);
fileInfo.setSize(size);
// 封装附件attachment
fileInfos.add(fileInfo);
} catch (FastDFSException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String listStr = "";
if (fileInfos.size() != 0){
listStr = gs.toJson(fileInfos);//把List转为JSON格式的字符串
}
// 存入数据库
noticeService.save(listStr);
return "redirect:" + Global.getAdminPath() + "/info/notice/record";
}