SpringBoot实现文件上传功能

网友投稿 1019 2022-11-24

SpringBoot实现文件上传功能

SpringBoot实现文件上传功能

经典的文件上传

服务器处理上传文件一般都是先在请求中读取文件信息,然后改变名称保存在服务器的临时路径下,最后保存到服务器磁盘中。本次以thymeleaf搭建demo,因此需要引入thymeleaf依赖库。

org.springframework.boot

spring-boot-starter-thymeleaf

2.5.5

如果使用的是gradle构建的项目,需要修改build.gradle文件:

compile 'org.springframework.boot:spring-boot-starter-thymeleaf:2.5.5'

新建一个Action类负责处理上传的文件:

@RestController

@RequestMapping("/upload/*")

public class UploadAction {

@PostMapping("/file")

public Object uploadHandler(HttpServletRequest request, String title, MultipartFile file) {

Map resultMap = new LinkedHashMap<>();

resultMap.put("title", title);

resultMap.put("filXGXNnbpEPeName", file.getName()); // 文件名

resultMap.put("originalFilename", file.getOriginalFilename()); // 原始名称

resultMap.put("content-type", file.getContentType()); // 文件类型

resultMap.put("fileSize", file.getSize() / 1024 + "K"); // 文件大小

try {

// 保存文件

String uploadedFilePath = saveFile(request, file.getInputStream(), file.getOriginalFilename()

.substring(file.getOriginalFilename().lastIndexOf(".") + 1));

resultMap.put("uploadedFilePath", uploadedFilePath); // 文件大小

} catch (IOException e) {

System.err.println("error-path: /upload/file, message: " + e.getMessage());

}

return resultMap;

}

/**

* 保存上传的文件到本地服务器

*

* @param request HttpServletRequest

* @param input 输入

* @param ext 文件扩展名

* @return 文件路径

* @throws IOException

*/

public String saveFile(HttpServletRequest request, InputStream input, String ext) throws IOException {

String realPath = request.getServletContext().getRealPath("/upload/file/"); // 取得服务器真实路径

File file = new File(realPath);

if (!file.getParentFile().exists())http:// { // 目录不存在

file.mkdirs(); // 创建多级目录

}

String filePath = realPath + UUID.randomUUID() + "." + ext;

// 取的文件输出

OutputStream out = new FileOutputStream(filePath);

byte[] data = new byte[2048]; // 缓冲数组2KB

int len = 0; // 读取字节长度

while ((len = input.read(data)) != -1) {

out.write(data, 0, len); // 文件写入磁盘

}

if (input != null) {

input.close();

}

out.close();

return filePath;

}

}

在resources目录下新建templates文件夹,在里面创建index.html文件作为项目首页展示。

标题:


文件:


启动项目,直接访问:http://localhost:8080/将进入index.html页面。

点击上传按钮,文件将被保存到服务器磁盘中:

SpringBoot对上传文件处理的简化

SpringBoot对FileUpload组件进行了整合,在文件保存的时候可以避免直接操作IO流,通过配置文件的方式指定文件上传的限制参数。修改application.yml文件:

server:

port: 8080

spring:

servlet:

multipart:

enabled: true # 启用文件上传

max-file-size: 1MB # 单文件上传最大限制

max-request-size: 10MB # 文件上传最大值

file-size-threshold: 10KB # 上传文件达到多大时写入磁盘

location: / # 临时文件存储位置

修改UploadAction,使用MultipartFile类的transferTo方法保存上传文件。

@RestController

@RequestMapping("/upload/*")

public class UploadAction {

@PostMapping("/file")

public Object uploadHandler(HttpServletRequest request, String title, MultipartFile file) {

Map resultMap = new LinkedHashMap<>();

resultMap.put("title", title);

resultMap.put("fileName", file.getName()); // 文件名

resultMap.put("originalFilename", file.getOriginalFilename()); // 原始名称

resultMap.put("content-type", file.getContentType()); // 文件类型

resultMap.put("fileSize", file.getSize() / 1024 + "K"); // 文件大小

try {

// 保存文件

String etc = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);

String serverPath = request.getScheme() + "://" + request.getServerName()

+ ":" + request.getServerPort() + request.getContextPath() + "/file/upload/";

String fileName = UUID.randomUUID() + "." + etc;

resultMap.put("filePath", serverPath + fileName); // 文件地址(服务器访问地址)

// 文件保存再真实路径下

File saveFile = new File(request.getServletContext().getRealPath("/file/upload/") + fileName);

if (!saveFile.getParentFile().exists()) { // 目录不存在,创建目录

saveFile.mkdirs();

}

file.transferTo(saveFile); // 保存上传文件

} catch (IOException e) {

System.err.println("error-path: /upload/file, message: " + e.getMessage());

}

return resultMap;

}

}

访问:http://localhost:8080/

点击上传按钮:

浏览器上访问filePath,可以预览上传的文件:

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:「分布式计算」Helix: 基于配额的任务调度
下一篇:原生js---无限滚动
相关文章

 发表评论

暂时没有评论,来抢沙发吧~