springboot中文件的上传和下载

添加依赖

    <!-- 文件上传所依赖的jar包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

在yml文件中进行配置

 #fileupload的最大上传大小
  spring:
  	servlet:
    	multipart:
     		max-file-size: 10485760
     		max-request-size: 10485760

文件上传的前台页面,form表单的enctype属性必须设置成multipart/form-data,前台使用了thymeleaf。

<form th:action="@{/saveFile}" method="post" enctype="multipart/form-data">
    <table>
        <tr>
            <td>图片:</td>
            <td><input type="file" name="myfile"></td>
        </tr>
        <tr>
            <td>发表用户头像:</td>
            <td><input type="file" name="myfile"></td>
        </tr>
        <tr>
            <td><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>

上传图片的封装的方法

 /**
     * 上传多张图片
     * @param file
     * @param list
     * @return
     */
    private List<String> saveFile(MultipartFile file, List<String> list) throws IOException {
        if (!file.isEmpty()) {
          /*
          项目服务器地址路径
         */
            File pfile = new ClassPathResource("/static/img/").getFile();
            //保存图片的路径
            //获取原始图片的拓展名
            String name = file.getOriginalFilename();
            assert name != null;
//            截取文件后缀名
            String originalFilename = name.substring(name.lastIndexOf("."));
            //创建新的文件名字
            String newFileName = UUID.randomUUID().toString().replace("-","") + originalFilename;

//            将文件名保存到数组中
            list.add(newFileName);

            //判断上传文件的保存目录是否存在
            if (!pfile.exists() && !pfile.isDirectory()) {
                System.out.println(pfile + "目录不存在,需要创建");
                //创建目录
                pfile.mkdir();
            }
            //创建文件
            File targetFile = new File(pfile, newFileName);
            //把本地文件上传到封装上传文件位置的全路径
            try {
                file.transferTo(targetFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

调用图片上传方法并将图片名保存在数据库中


    @PostMapping(value = "/saveFile")
    public void insertArticle(@RequestParam("myfile") MultipartFile[] files,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;chartSet=UTF-8");
        // 解决中文乱码问题
        response.setCharacterEncoding("UTF-8");

        List<String> list = new ArrayList<>();
        if (files != null && files.length > 0) {
            System.out.println("文件长度:"+files.length);
            for (MultipartFile file : files) {
                // 保存文件
                saveFile(file, list);
            }
        }

    }

图片的下载前台

<a th:href="@{/downLoad/p1.jpg}">下载文件</a>

后台

  @GetMapping("downLoad/{filename}")
    public void downLoad(@PathVariable("filename") String file,
                         HttpServletResponse response,
                         HttpServletRequest request) throws IOException {
    //          获取文件服务器真实路径的字节流
        InputStream inputStream = new ClassPathResource("/static/img/"+file).getInputStream();
//为了提高效率,使用字节缓冲流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

   //设置response响应头
        String mimeType = request.getServletContext().getMimeType(file);

        String userAgent = request.getHeader("User-Agent");

        String fileName="";

//        解决浏览器下载中文乱码问题
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")||userAgent.contains("Edge")){
            fileName= URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        }else {
           fileName= new String(file.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }

        response.setHeader("content-type",mimeType);
        // 下载文件能正常显示中文
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        
//获取输出流
        BufferedOutputStream outputStream =new BufferedOutputStream(response.getOutputStream());

       //        将输入流写入到输出流中
        IOUtils.copy(bufferedInputStream,outputStream);
//        关闭流
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(outputStream);

    }
以下是SpringBoot文件上传下载的步骤: 1. 创建SpringBoot项目并导入相关依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> ``` 2. 在application.properties文件配置文件保存路径: ```properties filePath=E:/springboot_save_file/ ``` 3. 创建文件上传的Controller: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import java.io.File; import java.io.IOException; @Controller public class FileUploadController { @Value("${filePath}") private String filePath; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:/"; } try { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); File destFile = new File(filePath + fileName); file.transferTo(destFile); redirectAttributes.addFlashAttribute("message", "File uploaded successfully"); } catch (IOException e) { e.printStackTrace(); redirectAttributes.addFlashAttribute("message", "Failed to upload file"); } return "redirect:/"; } } ``` 4. 创建文件下载的Controller: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class FileDownloadController { @Value("${filePath}") private String filePath; @GetMapping("/download/{fileName:.+}") public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) { Path file = Paths.get(filePath + fileName); Resource resource; try { resource = new UrlResource(file.toUri()); } catch (IOException e) { e.printStackTrace(); return ResponseEntity.notFound().build(); } return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } } ``` 5. 创建Thymeleaf模板文件index.html: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Spring Boot File Upload/Download</title> </head> <body> <h1>File Upload/Download</h1> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="Upload" /> </form> <p th:text="${message}"></p> <hr/> <h2>Download Files:</h2> <ul> <li th:each="file : ${files}"> <a th:href="@{/download/{fileName}(fileName=${file})}" th:text="${file}"></a> </li> </ul> </body> </html> ``` 6. 运行SpringBoot应用,并访问http://localhost:8080/,即可进行文件上传下载操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值