spring boot2 文件上传 + 删除 + 下载

# 新建 FilesController.class

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Api("文件上传接口")
@RestController
@RequestMapping("/api/file")
public class FilesController {

    /*
     * 本地文件上传路径
     * */
    private String filePath = "C:/image/";

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public Map<String, Object> upload(MultipartFile file) {
        if (file.isEmpty()) {
            return onResponse(500, "请选择一个文件上传");
        }

        String fileName = file.getOriginalFilename();
        Long fileSize = file.getSize();
        System.out.println("文件名:" + fileName);
        System.out.println("文件大小:" + fileSize/1024);

        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            //父目录不存在就创建一个
            dest.getParentFile().mkdir();
        }

        try {
            file.transferTo(dest);
            // 图片访问路径
            String path = "http://127.0.0.1:8833/image/" + fileName;
            return onResponse(200, path);
        } catch (IOException e) {
            e.printStackTrace();
            return onResponse(500, "文件上传失败");
        }
    }

    @ApiOperation("文件删除")
    @PostMapping("/delete")
    public Map<String, Object> delete(String name) {
        File file = new File(filePath + name);
        if (file.exists()) {
            if (file.delete()){
                return onResponse(200, "删除成功");
            } else {
                return onResponse(403, "删除失败");
            }
        } else {
            return onResponse(404, "文件不存在!");
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(HttpServletResponse response, String name) throws IOException {
        File file = new File(filePath + name);
        if (file.exists()) {
            response.setContentType("application/x-msdownload;charset=utf-8");// 设置强制下载不打开
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));// 设置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /*
     * 统一返回格式
     * */
    private Map<String, Object> onResponse(int code, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", code);
        map.put("msg", msg);

        return map;
    }
}


# application.properties

# 上传文件最大为 5MB
spring.servlet.multipart.max-file-size= 5MB
# 设置总上传的数据大小
spring.servlet.multipart.max-request-size= 5MB


# 新建 MyWebAppConfigurer.class

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 资源映射路径
 */
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**").addResourceLocations("file:C:/tests/");
    }
}

设置 url 访问路径



# 效果图

浪里个浪.gif



参考博客:

  1. SpringBoot2.x实现文件上传与下载
  2. SpringBoot 配置本地资源映射路径已解决
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值