Java常用小工具

本文介绍了如何在SpringBoot应用中处理文件上传和下载,包括设置HTTP响应头、处理文件路径和使用`URLEncoder`进行文件名编码。着重展示了`FileController`中的关键方法如`fileDownload`和`setAttachmentResponseHeader`。
摘要由CSDN通过智能技术生成

文件上传与下载

一、文件上传

二、文件下载

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
package com.shao.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/file")
public class FileController {
    @GetMapping("/download")
    public void fileDownload(@RequestParam("filename") String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {

        String basePath = "/tmp";
        String downloadPath = basePath + File.separator + filename;

        // 设置响应头
        setAttachmentResponseHeader(response, filename);
        // 写入数据
        writeBytes(downloadPath, response.getOutputStream());


    }

    /**
     * 设置文件下载的响应头
     *
     * @param response
     * @param realFileName
     * @throws UnsupportedEncodingException
     */
    public void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {

        // setContentType方法用于设置响应的内容类型(Content-Type),告诉客户端发送的数据是什么类型的
        // application/octet-stream
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

        // 将文件名编码
        String handlerPercentEncodeFilename = handlerPercentEncode(realFileName);
        // 设置请求头
        StringBuilder contentDispositionValue = new StringBuilder();
        // attachment; filename=:这部分指定了文件的下载方式,attachment 表示文件作为附件下载,而不是在浏览器中直接打开
        // filename:文件名字
        contentDispositionValue.append("attachment; filename=")
                // 编码后的文件名字,防止中文乱码
                .append(handlerPercentEncodeFilename)
                .append(";")
                // filename*=utf-8:这是一个扩展的 filename 参数,它指定了文件名的编码方式和语言。utf-8
                // 表示文件名采用 utf-8 编码。这个部分告诉客户端在下载文件时应该使用 utf-8 编码来解析文件名。
                .append("filename*=")
                .append("utf-8''")
                // 需要解析的文件名称
                .append(handlerPercentEncodeFilename);
        // Content-Disposition
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, contentDispositionValue.toString());


    }

    /**
     * 将文件名编码
     *
     * @param s 文件名
     * @return 返回编码后的文件名
     * @throws UnsupportedEncodingException
     */
    private static String handlerPercentEncode(String s) throws UnsupportedEncodingException {
        // 将文件编码
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
        // 将+替换为编码
        return encode.replaceAll("\\+", "%20");
    }

    /**
     * 写入
     *
     * @param filePath
     * @param os
     */
    public static void writeBytes(String filePath, OutputStream os) {
        File file = new File(filePath);
        try (FileInputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值