1.文件上传
/*文件上传*/
public static String uploadFile(MultipartFile file, String savePath) {
FileOutputStream out = null;
logger.info(savePath);
try {
File uploadPath = new File(savePath);
if (!uploadPath.exists()||uploadPath.isDirectory()) {
uploadPath.mkdirs();
}
/*转换成字节数组*/
byte[] bytes = file.getBytes();
/*获取原文件名*/
String originalFilename = file.getOriginalFilename();
/*构造新的文件名,避免同名文件覆盖*/
String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_" + new Random().nextInt(99999) + "_" + originalFilename;
/*指定文件上传路径*/
out = new FileOutputStream(uploadPath + "/" + newFileName);
out.write(bytes);
out.flush();
logger.info("文件上传成功");
return savePath+"/"+newFileName;
} catch (Exception e) {
logger.error("文件上传失败 -->> ", e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
logger.error("uploadFile error -->> ", e);
}
}
return null;
}
2.文件下载
/*文件下载:以流的方式*/
public static ResponseEntity downloadFile(String path, HttpServletResponse response) {
logger.info("传入路径参数" + path);
//设置文件路径
File file = new File(path);
//获取文件名
String fileName = file.getName();
logger.info("文件名" + file.getName());
response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
response.addHeader("Content-Length", "" + file.length());
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
os.flush();
} 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();
}
}
}
logger.info("下载成功");
return null;
}
3.fileUtil类完整代码
package com.bairuitech.anychat.file.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class FileUtil {
private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
/*文件上传*/
public static String uploadFile(MultipartFile file, String savePath) {
FileOutputStream out = null;
logger.info(savePath);
try {
File uploadPath = new File(savePath);
if (!uploadPath.exists()||uploadPath.isDirectory()) {
uploadPath.mkdirs();
}
/*转换成字节数组*/
byte[] bytes = file.getBytes();
/*获取原文件名*/
String originalFilename = file.getOriginalFilename();
/*构造新的文件名,避免同名文件覆盖*/
String newFileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "_" + new Random().nextInt(99999) + "_" + originalFilename;
/*指定文件上传路径*/
out = new FileOutputStream(uploadPath + "/" + newFileName);
out.write(bytes);
out.flush();
logger.info("文件上传成功");
return savePath+"/"+newFileName;
} catch (Exception e) {
logger.error("文件上传失败 -->> ", e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
logger.error("uploadFile error -->> ", e);
}
}
return null;
}
/*文件下载:以流的方式*/
public static ResponseEntity downloadFile(String path, HttpServletResponse response) {
logger.info("传入路径参数" + path);
//设置文件路径
File file = new File(path);
//获取文件名
String fileName = file.getName();
logger.info("文件名" + file.getName());
response.setContentType("application/octet-stream");//告诉浏览器输出内容为流
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
response.addHeader("Content-Length", "" + file.length());
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
os.flush();
} 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();
}
}
}
logger.info("下载成功");
return null;
}
}
4.控制层
//springboot上传文件出现异常java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured 加上这一段可以解决问题
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setDefaultEncoding("UTF-8");
multipartResolver.setMaxUploadSize(104857600);
return multipartResolver;
}
//文件上传
@RequestMapping("/upload")
public FileResult upload(MultipartFile file) {
String fileUrl = FileUtil.uploadFile(file, savePath);
return FileResult.success(fileUrl);
}
//文件下载
@RequestMapping("/download")
public FileResult download(HttpServletResponse response, String path) {
ResponseEntity responseEntity = FileUtil.downloadFile(path, response);
return FileResult.success("文件下载成功", responseEntity);
}
5.postMan测试文件上传成功
6.浏览器访问下载接口