本文使用springboot2,对文件的基础上传下载预览进行说明 直接上代码
依赖文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>demo5</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.7.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.7.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>7</source>
<target>7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
配置文件
# 设置最大上传大小
spring:
servlet:
multipart:
max-file-size: 100MB
# 设置上传路径
upload:
folder: D:/file/
download: /download?fileName=
返回结果
package com.fileExample.pojo;
public class Result {
private String status;
private Object msg;
private Object url;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Object getMsg() {
return msg;
}
public void setMsg(Object msg) {
this.msg = msg;
}
public Object getUrl() {
return url;
}
public void setUrl(Object url) {
this.url = url;
}
}
文件相关操作
package com.fileExample.controller;
import com.fileExample.pojo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
@RestController
public class FileController {
@Value("${upload.folder}")
private String root;
@Value("${upload.download}")
private String download;
/**
* 文件上传
* @param file
* @param request
* @return
*/
@PostMapping("/upload")
public Result fileUpload(MultipartFile file, HttpServletRequest request) {
Result result = new Result();
// 获取文件名称
String originalName = file.getOriginalFilename();
// 判断存放目录是否存在,不存在则创建
File folder = new File(root);
if (!folder.exists()) {
folder.mkdirs();
}
// 保存文件对象,uuid防止文件重名
String newName = UUID.randomUUID() + originalName.substring(originalName.lastIndexOf("."));
String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + newName;
try {
// 上传文件
// 如果需要上传数据库可以在此处稍作处理
file.transferTo(new File(folder, strNewFileName));
// 将文件下载地址或预览地址直接返回给前端,前端可以直接将文件进行预览
String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + download + strNewFileName;
result.setStatus("200");
result.setUrl(url);
} catch (IOException e) {
e.printStackTrace();
result.setStatus("500");
result.setMsg(e.getMessage());
}
return result;
}
/**
* 文件下载
* @param fileName
* @param response
*/
@GetMapping("/download")
public void download(String fileName, HttpServletResponse response) {
Path path = Paths.get(root + fileName);
if (Files.exists(path)) {
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
// 设置响应头类型
response.setContentType("application/" + fileSuffix);
try {
// 设置响应头
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
} catch (Exception e) {
e.printStackTrace();
}
try {
// 下载文件
Files.copy(path, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 文件预览
* @param fileName
* @param response
*/
@GetMapping("/preview")
public void preview(String fileName, HttpServletResponse response) {
Path path = Paths.get(root + fileName);
if (Files.exists(path)) {
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
// 根据文件类型设置合适的响应内容类型
if (fileSuffix.equalsIgnoreCase("jpg") || fileSuffix.equalsIgnoreCase("jpeg") || fileSuffix.equalsIgnoreCase("png") || fileSuffix.equalsIgnoreCase("gif")) {
response.setContentType("image/" + fileSuffix);
} else {
// 对于其他文件类型,可以根据需要设置不同的内容类型
// 或者生成预览内容,返回预览页面等
// 这里对于其他类型直接进行下载
response.setContentType("application/" + fileSuffix);
try {
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Files.copy(path, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}