spring boot实现文件上传下载
·
文章目录
前言
spring boot 项目中的上传,下载。
1. controller
import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import cn.hutool.core.util.ZipUtil;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping("/files")
public class FileController {
@Autowired
private FileService fileService;
/**
* 单一文件上传接口,上传失败由统一异常处理返回
* @param file
* @return
*/
@PostMapping("/uploadFile")
public R fileUpload(MultipartFile file){
if(file.isEmpty()){
return R.fail("请选择文件!");
}
String uploadFile = fileService.uploadFile(file);
return R.ok(uploadFile, "文件上传成功!");
}
@PostMapping("/uploadFiles")
public R filesUpload(MultipartFile[] files){
if(files.length <=0 ){
return R.fail("请选择文件!");
}
List<String> filesPath = fileService.uploadFiles(files);
return R.ok(filesPath, "文件上传成功!");
}
@GetMapping("/download")
public void fileDownload(HttpServletRequest request, HttpServletResponse response){
fileService.downloadFile(request, response);
}
// zip打包
@RequestMapping("/download/zip")
public void downloadForZip(HttpServletResponse response) throws IOException {
//这里设置打包后的zip文件名
String downloadName = "测试"+".zip";
try{
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + new String(downloadName.getBytes(),"ISO8859-1"));
}catch(UnsupportedEncodingException e){
System.out.println("----------下载文件名编码时出现错误------"+e.getMessage());
}
OutputStream outputStream = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(outputStream);
// 方式一:
// ZipArchiveOutputStream zous = new ZipArchiveOutputStream(outputStream);
// zous.setUseZip64(Zip64Mode.AsNeeded);
// zous.setEncoding("utf-8");
try{
//我这里是通过不同产品类型生成不同产品的二维码图片流
//具体你想生成什么类型的多个文件打包,只需要循环创建ArchiveEntry 然后zous.putArchiveEntry(entry)就可以了
// StoreProductType[] storeProductTypes = StoreProductType.values();
// for (StoreProductType storeProductType : storeProductTypes) {
// String url = "http://m.xxx.cn/goods/pay/xxx.html?productid="+storeProductType.getProductId()
// + "&agencycode="+ agencyId +"&channelid=def&appfrom=sqjk&isstore=1";
// //打包文件里的每个文件的名字
// String imgName = storeProductType.getDescription()+".png";
// ByteArrayOutputStream out = QRCode.from(url).to(ImageType.PNG).withSize(300,300).stream();
// byte[] bytes = out.toByteArray();
// ArchiveEntry entry = new ZipArchiveEntry(imgName);
// zous.putArchiveEntry(entry);
// zous.write(bytes);
// zous.closeArchiveEntry();
// if (out != null) {
// out.close();
// }
// 方式二:
String filePath = "http://192.168.1.138/group1/M00/00/00/wKgBvWBQY_OAaRBKAAIIxvji4o8112.pdf";
String[] strings = filePath.substring(accessPath.length()).split("/", 2);
String[] paths = new String[2];
InputStream[] ins = new InputStream[2];
for (int i=0; i<2; i++) {
//打包文件里的每个文件的名字
String imgName = "每个文件名" +i +".pdf";
paths[i] = imgName;
byte[] bytes = fastdfsClientService.download(strings[0], strings[1]);
ins[i] = new ByteArrayInputStream(bytes);
}
ZipUtil.zip(zos, paths, ins);
}catch (Exception e){
e.printStackTrace();
System.out.println("---------------生成打包流出错----------------"+e.getMessage());
}finally {
zos.close();
// zous.close();
if (outputStream != null) {
outputStream.close();
}
}
}
}
2. service
2.1 LocalFileServiceImpl
@Service
@Primary //用哪个实现
public class LocalFileServiceImpl implements FileService {
Logger logger = LoggerFactory.getLogger(LocalFileServiceImpl.class);
@Value("${file.upload.path}")
private String uploadPath;
@Value("${file.download.path}")
private String downloadPath;
@Override
public String uploadFile(MultipartFile file) {
String filename = file.getOriginalFilename();
File filePath;
try {
filePath = new File(uploadPath + filename);
// 检测是否存在目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();// 新建文件夹
}
file.transferTo(filePath);
logger.info("文件上传成功!");
return uploadPath + filename;
} catch (IOException e) {
logger.info("文件上传失败!");
throw new BaseException(e.getMessage());
}
}
@Override
public List uploadFiles(MultipartFile[] files) {
File filePath;
List<String> filesPath = new ArrayList<>();
for (int i = 0; i < files.length; i++) {
if (files[i].isEmpty()) {
throw new BaseException("上传第\" + (i++) + \"个文件失败");
}
String fileName = files[i].getOriginalFilename();
filePath = new File(uploadPath + fileName);
try {
// 检测是否存在目录
if (!filePath.getParentFile().exists()) {
filePath.getParentFile().mkdirs();// 新建文件夹
}
files[i].transferTo(filePath);
logger.info("第" + (i + 1) + "个文件上传成功");
filesPath.add(uploadPath + fileName);
} catch (IOException e) {
logger.error(e.toString(), e);
throw new BaseException("上传第\" + (i++) + \"个文件失败");
}
}
return filesPath;
}
@Override
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "服务器及终端配置.xlsx";// 文件名
if (fileName != null) {
//设置文件路径
File file = new File(downloadPath + fileName);
//File file = new File(realPath , fileName);
if (file.exists()) {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("utf-8"),"ISO8859-1"));// 设置文件名
byte[] buffer = new byte[1024];
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);
}
logger.info("下载成功!");
} catch (Exception e) {
logger.info("下载失败!");
throw new BaseException("下载失败!" + e.getMessage());
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
2.2 FastDFSFileServiceImpl
@Service
public class FastDFSFileServiceImpl implements FileService {
@Override
public String uploadFile(MultipartFile file) {
return null;
}
@Override
public List<String> uploadFiles(MultipartFile[] files) {
return null;
}
@Override
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
}
}
3. 配置文件
# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB
#文件:
file.upload.path=D:/code/test/user/data/upload/
file.download.path=D:/code/test/user/data/download/
FastDFS相关,有机会补充
更多推荐
所有评论(0)