文件上传下载工具类
工具类
package cn.sntsoft.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
/**
* @author pengxin
* @version 1.0
* @date 2020/12/31 10:47
*/
@Slf4j
public class FileUtils {
/**
* 下载文件
*/
public static String downloadFiles(HttpServletRequest request, HttpServletResponse response,String fileName){
if (fileName.isEmpty()){
return "文件名不能为空";
}
//设置文件路径
ClassPathResource pathResource = new ClassPathResource("static/images/" + fileName);
File file = null;
try {
file = pathResource.getFile();
System.out.println(file);
} catch (IOException e) {
e.printStackTrace();
return "文件不存在!";
}
response.setHeader("content-type","application/octet-stream");
//设置强制下载不打开
response.setContentType("application/force-download");
//设置文件名
response.addHeader("Content-Disposition","attachment;fileName="+fileName);
byte[] buffer = new byte[1024];
InputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
ServletOutputStream stream = response.getOutputStream();
int read = bis.read(buffer);
while (read != -1){
stream.write(buffer,0,read);
read = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "文件下载成功";
}
/**
* 判断文件大小
* @param file 文件
* @param size 限制大小
* @param unit 限制单位(B,K,M,G)
*/
public static boolean checkFileSize(MultipartFile file, int size,String unit){
if (file.isEmpty() || StringUtils.isEmpty(size) || StringUtils.isEmpty(unit)){
return false;
}
long lent = file.getSize();
double fileSize = 0;
if ("B".equals(unit.toUpperCase())) {
fileSize = (double) lent;
} else if ("K".equals(unit.toUpperCase())) {
fileSize = (double) lent / 1024;
} else if ("M".equals(unit.toUpperCase())) {
fileSize = (double) lent / 1048576;
} else if ("G".equals(unit.toUpperCase())) {
fileSize = (double) lent / 1073741824;
}
if (fileSize > size) {
return false;
}
return true;
}
/**
* 封装单个上传方法
*/
public static String upload(MultipartFile file){
if (file.isEmpty()){
return "文件夹为空";
}
//获取文件大小
long fileSize = file.getSize();
log.info("文件大小:"+fileSize);
//判断文件的大小
if (!FileUtils.checkFileSize(file,50,"M")){
log.error("上传文件规定小于50MB");
return "上传文件规定小于50MB";
}
//获取文件名
String filename = file.getOriginalFilename();
log.info("上传的文件名:"+filename);
//获取文件后缀名
String lastName = filename.substring(filename.lastIndexOf("."));
log.info("文件后缀名:"+lastName);
///设置文件存储路径
String filePath = "D:/file/";
String path = filePath + filename;
File dest = new File(path);
//检测文件是否存在
if (dest.getParentFile().exists()){
dest.getParentFile().mkdirs();//创建文件夹
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
/**
* 多文件上传
*/
public static String handleFileUpload(HttpServletRequest request){
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size();i++){
file = files.get(i);
String path = "D:/file/";
if (!file.isEmpty()){
try {
byte[] bytes = file.getBytes();
log.info("文件内容"+bytes);
stream = new BufferedOutputStream(new FileOutputStream(
new File(path + file.getOriginalFilename())));//设置文件夹路径及名字
stream.write(bytes);//写入
stream.close();
} catch (Exception e) {
e.printStackTrace();
return "第"+ i +"文件上传失败"+e.getMessage();
}
}else {
return "第"+ i +"个文件上传失败因为文件为空";
}
}
return "上传成功";
}
}
controller
package cn.sntsoft.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
/**
* @author pengxin
* @version 1.0
* @date 2020/12/31 10:37
*/
@RestController
@Slf4j
public class FileDownUpController {
/**
* 单文件上传
* @param file
* @return
*/
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file){
String result= FileUtils.upload(file);
if (result == null){
return null;
}
return result;
}
/**
* 多文件上传
*/
@RequestMapping("/batch")
public String handleFileUpload(HttpServletRequest request){
String result = FileUtils.handleFileUpload(request);
if (result == null){
return null;
}
return result;
}
/**
* 文件下载
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "1.jpg";// 文件名
String result = FileUtils.downloadFiles(request, response, fileName);
if (request == null) {
return null;
}
return result;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>单文件上传</p>
<form action="upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>文件下载</p>
<a href="download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form action="batch" method="POST" enctype="multipart/form-data">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上传"/></p>
</form>
</body>
</html>