工作里面需要使用文件传输功能,我写了一个比较简单的工具类实现大部分文件的上传,欢迎大家学习和评论。
项目是springboot,需要下载maven,jdk,IDEA,这些基本的东西我就不在多说了。
工具类代码:
package com.example.demo.util;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
-
@Author: wjy
-
@DateTime: 2021/1/13 16:44
-
@ClassName FileUploadUtil
-
各种文件上传的工具类
*/
public class FileUploadUtil {
//定义允许上传的文件扩展名
private static String suffixs = “gif,jpg,jpeg,png,bmp,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4,doc,docx,xls,xlsx,ppt,txt,zip,rar,gz,bz2,amr,m4a,aif”;/**
*-
@param uploadFiles 上传的文件资源
-
@param savePath 保存的路径
-
@return
*/
public static Map<String,String> uploadFile(MultipartFile[] uploadFiles, String savePath) throws IOException {
Map<String,String> ret = new HashMap<>();
if(null == uploadFiles) {
ret.put(“msg”,“请选择文件”);
ret.put(“type”,“error”);
return ret;
}
for(MultipartFile file : uploadFiles) {
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1,file.getOriginalFilename().length());
if(!suffixs.contains(suffix)) {
ret.put(“msg”,“文件的后缀名不符合,文件必须以:” + suffixs.toString() + " 结尾");
ret.put(“type”,“error”);
return ret;
}
if(file.getSize() > 1024 * 1024 * 800){
//文件没有选择
ret.put(“type”, “error”);
ret.put(“msg”, “文件大小超过800M,请上传小于800M的文件!”);
return ret;
}
File filePath = new File(savePath);
if(!filePath.exists()) { //如果目录不存在,创建目录
filePath.mkdirs();
}
//把文件转存到这个文件夹下
String filename = new Date().getTime() + “.” + suffix;
file.transferTo(new File(savePath + filename ));}
ret.put(“msg”,“上传成功”);
ret.put(“type”,“true”);
ret.put(“filepath”,savePath);
return ret;
}
-
}
控制器代码:
package com.example.demo.util.controller;
import com.example.demo.util.FileUploadUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
/**
-
@Author: wjy
-
@DateTime: 2021/1/13 18:14
-
@ClassName FileController
*/
@Controller
@RequestMapping("/file")
public class FileController {/**
- 上传文件
- @param
- @param request
- @return
- @throws IOException
*/
@RequestMapping(value="/upload_photo",method= RequestMethod.POST)
@ResponseBody
public Map<String, String> uploadPhoto(MultipartFile[] files, HttpServletRequest request) throws IOException {
return FileUploadUtil.uploadFile(files,“D://resources/upload/”);
}
}
yml配置文件代码;
spring:
servlet:
multipart:
max-file-size: 800MB
max-request-size: 800MB