在日常开发中我们会在某些功能需求中使用到java文件上传和下载百度搜索的时候太乱又容易踩坑。
为了避免大家浪费上网搜索的时间 工具类中各方法均写上注释信息便于大家理解
我将个人总结归纳如下 => 个人总结工具类附上希望能对大家有所帮助。
一、 工具类详情
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* @author zhu
* @date 2021/1/21 13:43
*/
public class FileUpUtils {
/**
* 上传文件
*
* @param file 文件
* @param path 绝对路径
* @return flag
*/
public static Boolean upFile(MultipartFile file, String path) {
//获取上传文件名,包含后缀
String originalFilename = file.getOriginalFilename();
//获取后缀
String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//保存的文件名 or 避免文件重复名称
// String dFileName = UUID.randomUUID()+substring;
//保存路径 服务器文件路径
//String path = "C:\\FileTest\\";
//生成保存文件
File uploadFile = new File(path + originalFilename);
//将上传文件保存到路径
try {
file.transferTo(uploadFile);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 获取文件大小 转换为 M
*
* @param file 文件
* @return M
*/
public static Double fileSize(MultipartFile file) {
long size = file.getSize();
Double fileSize = size * 0.00000095367432;
return fileSize;
}
/**
* 获取文件服务器绝对路径
* 路径参数拼接
*
* @param file 文件
* @param path 服务器路径
* @return 路径
*/
public static String getLocalPath(MultipartFile file, String path) {
String originalFilename = file.getOriginalFilename();
String localPath = path + originalFilename;
return localPath;
}
/**
* 获取下载文件
*
* @param response 返回
* @param url url地址
* @return 浏览器文件下载
* @throws UnsupportedEncodingException 异常
*/
public static String downLoad(HttpServletResponse response, String url) throws UnsupportedEncodingException {
String filename = FileUpUtils.getFilename(url);
File file = new File(url);
//判断文件父目录是否存在
if (file.exists()) {
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));
byte[] buffer = new byte[1024];
//文件输入流
FileInputStream fis = null;
BufferedInputStream bis = null;
//输出流
OutputStream os = null;
try {
os = response.getOutputStream();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer);
i = bis.read(buffer);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("----------file download---" + filename);
try {
bis.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
* 获取Url路径中文件名
*
* @param url
* @return
*/
public static String getFilename(String url) {
File tempFile = new File(url.trim());
String fileName = tempFile.getName();
return fileName;
}
}
一、文件上传
在这里不做太多演示大家大概看看效果和Controller层代码 接口调用
@ApiOperation("新增模块 文件上传")
@PostMapping("/addModuleFile")
public APIResponse addModuleFile(@RequestPart("file") MultipartFile file,
) throws Exception {
if (file.isEmpty()) {
APIResponse.fail("上传文件不存在 请重新上传");
}
return moduleService.addModuleFile(file);
service层
@Override
public APIResponse addModuleFile(MultipartFile file) throws Exception {
//文件上传
Boolean flag = this.UploadFile(file);
if (flag == false) {
//文件上传失败
return APIResponse.fail("文件上传服务器失败 请联系管理员");
}
return APIResponse.success("文件已成功");
}
这里使用Postman调用接口
注意请求方式 多个参数可添加key 和Value controller正常接受就行不用添加其他注解
二、文件下载
/**
* @author zhu
* @date 2021/1/25 15:06
*/
@RequestMapping("/test")
@RestController
public class Test {
@NotLoginAccess
@RequestMapping("/download")
public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
String files ="C:\\FileTest\\commons-dbcp-1.4.jar";
return FileUpUtils.downLoad(response,files);
}
Service层:
直接调用了工具类方法 省去了Service方法
结果演示:
三、补充
关于设置文件大小限制
#上传文件大小
spring.servlet.multipart.maxFileSize = 600000
spring.servlet.multipart.maxRequestSize=600000
application 文件参数获取: