首页 > 其他分享 >springboot上传下载文件原来这么丝滑

springboot上传下载文件原来这么丝滑

时间:2023-01-19 17:35:04浏览次数:38  
标签:丝滑 springboot 上传下载 upload filename str import response String

我使用了hutool的 FileUtil,IdUtil,所以需要引入hutool:

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.11</version>
        </dependency>

 

application.yml 中定义上传文件目录:

files:
  upload:
    path: D:/java_workspace/springboot_demo/upload/

 

上传页面:

<form action="/files/upload" method="post" enctype="multipart/form-data">
    <div><input type="file" name="file"></div>
    <div><input type="submit" value="上传"></div>
</form>

 

上传下载处理:

package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

@RestController
@ResponseBody
@RequestMapping(value ="/files")
public class Files {
    @Value("${files.upload.path}")
    private String fileUploadPath;

    //上传
    @PostMapping(value ="/upload")
    public String upload(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String originalFilename = file.getOriginalFilename(); //文件名.jpg
        String type = FileUtil.extName(originalFilename);//.jpg
        long size = file.getSize();//大小

        String uuid = IdUtil.fastSimpleUUID();
        String filename = uuid + "." + type;
        File uploadFile = new File(fileUploadPath +"/"+ filename);

        //先存储到磁盘
        if (!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdirs();
        }

        file.transferTo(uploadFile);

        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html;charset=utf-8");
        response.setContentType("text/html;charset=utf-8");

        String str = "";
        str += "<html lang=\"zh-CN\">\n";
        str += "<head>\n";
        str += "<meta charset=\"utf-8\">\n";
        str += "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">\n";
        str += "</head>\n";
        str += "<body>\n";
        str += "file: "+originalFilename+" upload success, <br /><a href='/files/download/"+filename+"' target" +
                "='_blank'>download" +
                "</a" +
                ">\n";
        str += "</body>\n";
        str += "</html>\n";

        return str;
    }

    //下载
    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) throws IOException {
        File uploadFile = new File(fileUploadPath +"/"+ filename);
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Contene-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
        response.setContentType("application/octet-stream");

        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}

 

效果:

 

 

 

 

 

 

标签:丝滑,springboot,上传下载,upload,filename,str,import,response,String
From: https://www.cnblogs.com/xuxiaobo/p/17061859.html

相关文章

  • SpringBoot @Target、@Retention、@Documented注解简介
    jdk1.5起开始提供了4个元注解:@Target、@Retention、@Documented、@Inherited。何谓元注解?就是注解的注解。在程序开发中,有时候我们需要自定义一个注解,这个自定义注解类就......
  • SpringBoot日志框架分析
    本文简介第一部分,介绍spring-jcl适配各种日志框架的方式第二部分,介绍slf4j适配各种日志框架的方式第三部分,介绍下logback框架的使用及原理 一、spring-jcl分析说......
  • springboot整合es
    pom.xml增加依赖(注意版本要和springboot匹配)<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-st......
  • springboot 热更 2023.3
    热更使用devtools或者alt+shit+f9ideaFile|Settings|Preferences|Build,Execution,Deployment|Compiler:BuildprojectautomaticallyFile|Setting......
  • springboot 常用项目结构
    servicex//项目名|-admin-ui//管理服务前端代码(一般将UI和SERVICE放到一个工程中,便于管理)|-servicex-auth//模块1......
  • SpringBoot(三)
    Swagger、分布式架构部分​​11、Swagger​​​​11.1、Swagger简介​​​​11.2、SpringBoot集成Swagger​​​​11.3、配置Swagger​​​​11.4、Swagger配置扫描接口​​......
  • SpringBoot(二)
    模板引擎、数据源、安全框架部分​​5、SpringBootWeb开发​​​​5.1、静态资源​​​​5.2、首页​​​​5.3、Thymeleaf模板引擎​​​​5.4、装配扩展SpringMVC​​​......
  • SpringBoot+MyBatils-puls+db2
    记录自己搭建db2数据库,链接数据库遇到的问题。 搭建db2我是在阿里云使用docker搭建的db2数据库,搭建数据库参考下面这个链接https://www.cnblogs.com/Yongzhouunknown/p......
  • SpringBoot源码学习3——SpringBoot启动流程
    系列文章目录和关于我一丶前言在《SpringBoot源码学习1——SpringBoot自动装配源码解析+Spring如何处理配置类的》中我们学习了SpringBoot自动装配如何实现的,在《Sprin......
  • 230118_50_SpringBoot入门
    yaml配置文件中,支持占位符配置person:name:bill${random.int}age:4happy:truebirth:2023/01/15maps:{k1:v1,k2:v2}hello:hellolists:-cat-dog-fish......