您当前的位置: 首页 >  Java

彭世瑜

暂无认证

  • 1浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Java:SpringBoot实现文件上传

彭世瑜 发布时间:2020-07-16 21:01:11 ,浏览量:1

后端上传代码如下

package com.mouday.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传
 * 参考
 * https://blog.csdn.net/gnail_oug/article/details/80324120
 */
@Controller
public class FileController {
    // 获取上传测试页面
    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }

    // 单文件上传
    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            return "file is Empty";
        }

        String filename = file.getOriginalFilename();

        try {
            File path = this.getUploadDirectory();
            File dest = new File(path, filename);
            System.out.println(dest.getPath());
            file.transferTo(dest);

            return new File("/upload", filename).toString();

        } catch (IOException e) {
            e.printStackTrace();
            return "error";
        }
    }

    // 多文件上传
    @PostMapping("/multiUpload")
    @ResponseBody
    public List upload(@RequestParam("file") List files) {
        List list = new ArrayList();

        for (MultipartFile file : files) {
            list.add(this.upload(file));
        }
        return list;
    }


    /**
     * 获取文件保存路径
     * 参考:https://www.bbsmax.com/A/GBJrE67Wz0/
     *
     * @return
     * @throws FileNotFoundException
     */
    public File getUploadDirectory() throws FileNotFoundException {
        String pathName = ResourceUtils.getURL("classpath:").getPath();
        File path = new File(pathName, "/public/upload");

        if (!path.exists()) {
            path.mkdirs();
        }

        return path;
    }

}

前端代码

src/main/resources/templates/upload.html




    
    Title



单文件上传

    
    


多文件上传

    
    
    
    




因为前端页面需要使用模板引擎,所以需要引入依赖


    org.springframework.boot
    spring-boot-starter-thymeleaf

application.properties 配置上传的文件大小限制

# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=10MB

参考

  1. Spring Boot教程(十三):Spring Boot文件上传
  2. Spring Boot 上传文件 获取项目根路径 物理地址 resttemplate上传文件
关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.0811s