AI智能
改变未来

SpringBoot学习:文件上传和下载


maven导入依赖

首先创建一个maven项目,然后加入以下配置,就创建好了一个springboot项目

  <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.5.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>

项目

主要是实现文件的上传和下载,所以项目结构很简单

先看一下配置文件,SpringBoot提供了文件解析类,我们需要去配置一些参数

主要是限制上传文件的大小

然后是上传文件的工具类,这里是自己写的文件操作,(使用commons-fileupload和commons-io这些写好的工具更好)

package com.david.learn.utlis;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.*;import java.net.URLEncoder;public class FileUtils {/**** @param input 输入的文件流* @param filePath  文件要保存的路径* @throws IOException*/public static void upload(InputStream input, File filePath) throws IOException {FileOutputStream output = new FileOutputStream(filePath);byte[] bytes = new byte[4096];int n ;while (-1  != (n = input.read(bytes)) ) {output.write(bytes,0,n);}}/*** 将文件下载到客户端** @param filePath* @param fileName* @param response* @param isOnLine 是否在线打开* @throws Exception*/public static void download(String filePath, String fileName, HttpServletRequest request,HttpServletResponse response, boolean isOnLine) throws Exception {File f = new File(filePath);BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] buf = new byte[1024];int len = 0;response.reset(); // 非常重要// 解决文件名中文乱码问题String fileNameDisplay = URLEncoder.encode(fileName, \"UTF-8\");// 针对火狐浏览器需要特殊处理if (\"FF\".equals(getBrowser(request))) {fileNameDisplay = new String(fileName.getBytes(\"UTF-8\"), \"iso-8859-1\");}// 在线打开方式if (isOnLine) {response.setHeader(\"Content-Disposition\", \"inline; filename=\" + fileNameDisplay);}// 纯下载方式else {response.setContentType(\"application/x-msdownload\");response.setHeader(\"Content-Disposition\", \"attachment; filename=\" + fileNameDisplay);}OutputStream out = response.getOutputStream();while ((len = br.read(buf)) > 0) {out.write(buf, 0, len);}out.flush();br.close();out.close();}/*** 判断客户端浏览器类型** @param request* @return*/private static String getBrowser(HttpServletRequest request) {String UserAgent = request.getHeader(\"USER-AGENT\").toLowerCase();if (UserAgent != null) {if (UserAgent.indexOf(\"msie\") >= 0) {return \"IE\";}if (UserAgent.indexOf(\"firefox\") >= 0) {return \"FF\";}if (UserAgent.indexOf(\"safari\") >= 0) {return \"SF\";}}return null;}}

在写controller代码之前,还需要写一个接口调用后返回的响应类

package com.david.learn.dto;import lombok.AllArgsConstructor;import lombok.Data;@Data@AllArgsConstructorpublic class BaseReturnDto {// 返回码private int code;// 结果说明private String msg;}

最后是controller的代码,总共写了三个接口,分别是上传文件、下载文件、在线查看文件

  • 查看文件还得看浏览器是否支持,一般查看pdf文件是可以的
package com.david.learn.controller;import com.david.learn.dto.BaseReturnDto;import com.david.learn.utlis.FileUtils;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;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;@RestControllerpublic class FileOperateController {// 当前项目绝对路径private static final String PROJECT_PATH = new File(\"\").getAbsolutePath();// 文件上传的路径private static final String UPLOAD_PATH = PROJECT_PATH + \"/upload/\";// 最好手动在项目里创建文件夹,如果不想手动创建,加上这段代码static {// 项目里没有upload这个文件夹时,会自动创建File file = new File(UPLOAD_PATH);if (!file.exists()){if (!file.mkdirs()) {throw new RuntimeException(\"创建文件夹失败\");}}}/*** 文件上传*/@PostMapping(\"/uploadFile\")// 使用数组可以实现多文件上传,单文件的话不用数组public BaseReturnDto uploadFile(MultipartFile[] multipartFile) throws IOException {for (MultipartFile file : multipartFile) {String fileLocation = UPLOAD_PATH + file.getOriginalFilename();FileUtils.upload(file.getInputStream(), new File(fileLocation));}return new BaseReturnDto(200, \"文件上传成功\");}/*** 文件下载*/@GetMapping(\"/downloadFile/fileName/{fileName}\")public BaseReturnDto download(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {try {FileUtils.download(UPLOAD_PATH + fileName, fileName, request, response, false);return new BaseReturnDto(200, \"文件下载成功\");} catch (Exception e) {e.printStackTrace();return new BaseReturnDto(500, \"文件下载失败\");}}/*** 在线查看文件*/@GetMapping(\"/watchFile/fileName/{fileName}\")public BaseReturnDto watch(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {try {FileUtils.download(UPLOAD_PATH + fileName, fileName, request, response, true);return new BaseReturnDto(200, \"文件查看成功\");} catch (Exception e) {e.printStackTrace();return new BaseReturnDto(500, \"文件查看失败\");}}}

测试接口

使用postman测试接口,结果完美

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » SpringBoot学习:文件上传和下载