springboot 实现单文件上传/多文件上传/文件下载

java 开发经常需要用到文件上传,接下来博主就创建一个springboot项目,实现单文件上传/多文件上传/文件下载功能

1.先看一下博主的项目结构图

2.application.yml主要配置

3.如上图创建项目

创建FileUpload类:

package com.study.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileUpload {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileUpload.class);

    @Value("${upload.path}")  //在application中配置的上传地址:
    private String uploadPath;
    @PostMapping("/upload")
    //单文件上传
    public Boolean upload(@RequestParam("file") MultipartFile file) {
        BufferedOutputStream stream = null;
        try {
            if (file.isEmpty()) {
                LOGGER.info("文件为空:");
                return false;
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            LOGGER.info("上传的文件名为:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            LOGGER.info("文件的后缀名为:" + suffixName);

            File dest = new File(uploadPath + fileName);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            LOGGER.info("文件的上传路径:" + uploadPath);
            return true;
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    //多文件上传
    @PostMapping("/uploadMore")
    public boolean handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String fileName = file.getOriginalFilename();
                    File dest = new File(uploadPath + fileName);
                    file.transferTo(dest);
                } catch (Exception e) {
                    LOGGER.info("第{0}个文件上传失败 ==>{1} ",i,e.getMessage());
                    return false;
                }
            } else {
                LOGGER.info("第{0}个文件为空,上传失败 ",i);
                return false;
            }
        }
        return true;
    }
}

文件上传:

接下来使用接口测试工具postman测试:(注意:这里测试的单文件上传接口,多文件上传接口同理

查看上传文件:

 文件下载:

1.配置拦截器,拦截器代码,在哪里配置请参考文章开始目录结构图

package com.study.controller.config;

import org.springframework.beans.factory.annotation.Value;
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 {
    @Value("${upload.path}")  //application中配置的文件上传路径
    private String path;      
    @Value("${upload.staticPath}")  //application中配置的浏览器中的映射路径
    private String staticPath;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //当用户访问http://localhost:8080/api/file/WeChat Image_20190928085046.jpg的时候
        //会把api/file映射为本地真实路径
        //这里会把上面这个访问地址映射为:
        //http://localhost:8080/G:/IdeaWorkSpace/MyStudyCollection/upload//WeChat //Image_20190928085046.jpg
        registry.addResourceHandler(staticPath +"/**").addResourceLocations("file:" + path);
    }
}

启动项目访问:http://localhost:8080/api/file/WeChat%20Image_20190928085046.jpg(图片自动打开,其他文件提示下载)

 

springboot实现单文件上传/多文件上传/文件下载就完成了

项目git地址:https://gitee.com/Vince-ZZ/MyStudyCollection/tree/master/study-web

关注我的公众号:程序员小栈
一起来交流学习吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值