Spring文件上传下载代码

Spring文件上传下载代码

文件上传

MultipartFile是SpringMVC提供简化上传操作的工具类。

java 复制代码
	/**
     * 文件上传接口
     *
     * @param file
     * @return
     */
    @PostMapping("/fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file) {
        // 用户鉴权,判断有无权限上传,此处逻辑省略

        // 文件判空
        if (file.isEmpty()) {
            return "上传失败,文件为空";
        }
        List<String> suffixList = new ArrayList<String>() {{
            add("pdf");
            add("xls");
        }};
        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 校验文件后缀
        if (!suffixList.contains(suffix)) {
            return "文件类型不合法";
        }

        // 限制文件大小 5M , file.getSize()单位为字节
        if (file.getSize() > 5 * 1024 * 1024) {
            return "文件大小超出限制";
        }

        try {
            // 构建文件名
            // 获得当前项目所在文件夹
            String fileDir = System.getProperty("user.dir") + File.separator + "/file/";
            String fileName = "MyFile";
            // 首次上传需先创建文件夹
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 保存文件
            file.transferTo(new File(fileDir + fileDir + "." + suffix));

        } catch (Exception e) {
            return "文件上传失败";
        }
        return "文件上传成功";
    }

文件下载:

java 复制代码
	@GetMapping("fileDownLoad")
    public void fileDownLoad(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        try{
            String fileName = "Myfile.exe";
            String absolutePath = System.getProperty("user.dir") + File.separator + "/file/" + fileName;
            File file = new File(absolutePath);
            fileInputStream = new FileInputStream(file);
            // 设置response 头部
            response.reset();
            response.setContentType("application/load;charset=UTF-8");
             //Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.setHeader("Content-Disposition", "attachment;filename="
            + new String(file.getName().getBytes("utf-8"), "iso-8859-1"));
            // 将输入流数据写入到响应输出流中
            ServletOutputStream sos = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while((len = fileInputStream.read(b)) > 0) {
                sos.write(b, 0, len);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if(fileInputStream != null) {
                try{
                    fileInputStream.close();
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                }
            }
        }
    }
相关推荐
Resean02237 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存
在爪洼山玩泥巴7 小时前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生17 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵17 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰18 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai
Flynn Liang18 小时前
流量治理不是限流那么简单:I/O 密集型 Java 服务的 6 层防线
java·微服务·高并发·限流·熔断·系统稳定性·resilience4j
学长毕设18 小时前
基于SpringBoot智慧养老服务平台设计与实现-附源码
java·spring boot·后端
曹牧19 小时前
Java:“刷新雪崩”
java·开发语言
秋天的怀念_David19 小时前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
千寻技术帮20 小时前
10454_基于Springboot的企业购销链管理系统
spring boot·mysql·vue·毕业设计·进销存