SpringBoot文件上传, 上传到项目的相对路径上

1.准备工作

1、新建一个SpringBoot项目加上web依赖, 所有依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf-spring5</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-test</artifactId>
	<scope>test</scope>
</dependency>

2、application.properties

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

# 文件上传路径
pro.uploadPath=/uploadFile

#spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/uploadFile/

3、新建文件上传的静态文件 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
    <body>
        <h1>单文件上传</h1>
        <form method="post" action="/file/upload" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>

        <h1>传统手艺文件上传</h1>
        <form method="post" action="/upload" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>

        <h1>多文件上传</h1>
        <form method="post" action="/uploads" enctype="multipart/form-data">
            <input type="file" name="file"><br>
            <input type="file" name="file"><br>
            <input type="submit" value="提交">
        </form>
    </body>
</html>


2.文件上传代码

package com.pro.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UploadController {
    @Value("${pro.uploadPath}")
    private String uploadPath;

    public final static String UPLOAD_PATH_PREFIX = "src/main/resources/static";

    /**
     * 获取文件路径
     * @param request 请求体
     * @param fileName 文件名称
     * @return 文件路径
     */
    public String getUploadPath(HttpServletRequest request, String fileName) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + uploadPath + "/" + fileName;
    }

    @GetMapping("/hello")
    public String hello(HttpServletRequest request) {
        System.out.println("uploadPath --> " + uploadPath);
        System.out.println("上下文2 --> " + request.getServletContext().getRealPath("/file"));

        File file = new File(UPLOAD_PATH_PREFIX);
        System.out.println("UPLOAD_PATH_PREFIX 路径: " + file.getAbsoluteFile());

        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            System.out.println("ResourceUtils.getURL.getPath --> " + path);

            System.out.println("当前项目的绝对路径 --> " + new File("").getAbsolutePath());
            System.out.println("upload 绝对路径 --> " + new File("upload").getAbsolutePath());
            System.out.println("/upload 绝对路径 --> " + new File("/upload").getAbsolutePath());
            System.out.println("./upload 绝对路径 --> " + new File("./upload").getAbsolutePath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        return format;
    }

    // 单文件上传
    @RequestMapping("/file/upload")
    public Object fileUpload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        Map<String, Object> map = new HashMap();
        map.put("msg", "上传成功");

        if (multipartFile.isEmpty()) {
            map.put("msg", "空文件");
            return map;
        }

        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        if ("".equals(fileName)) {
            map.put("msg", "文件名不能为空");
            return map;
        }
        System.out.println("上传文件原始的名字: " + fileName);

        // 使用uuid生成新文件名
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("保存的文件的新名字: " + newFileName);

        // 获取年月日的日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());

        // 生成以日期分割的文件路径
        File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + format);
        System.out.println("存放的文件夹: " + readPath);
        System.out.println("存放文件的绝对路径: " + readPath.getAbsolutePath());
        // 判断文件夹是否存在
        if (!readPath.isDirectory()) {
            // 创建文件夹
            readPath.mkdirs();
        }

        // 文件真实的保存路径
        File file = new File(readPath.getAbsolutePath() + File.separator + newFileName);
        try {
            multipartFile.transferTo(file);

            // 获取存储路径
            String filePath = getUploadPath(request, format + "/" + newFileName);
            map.put("path", filePath);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg", "上传失败");
        }

        return map;
    }

    // 传统手艺
    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile multipartFile) {
        Map<String, Object> map = new HashMap();
        map.put("msg", "上传成功");

        if (multipartFile.isEmpty()) {
            return "文件不能为空";
        }

        String fileName = multipartFile.getOriginalFilename();
        if ("".equals(fileName)) {
            return "文件名不能为空";
        }
        System.out.println("文件名: " + fileName);

        File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + "temp");
        if (!readPath.isDirectory()) {
            readPath.mkdirs();
        }
        System.out.println("保存路径: " + readPath);

        InputStream is = null;
        FileOutputStream os = null;
        try {
            is = multipartFile.getInputStream();
            os = new FileOutputStream(new File(readPath, fileName));

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = is.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg", "上传失败");
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return map;
    }

    // 多文件上传
    @PostMapping("/uploads")
    public String uploads(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");

        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                return file.getOriginalFilename() + "上传失败";
            }

            File readPath = new File(UPLOAD_PATH_PREFIX + uploadPath + File.separator + "temps");
            System.out.println("多文件上传的位置: " + readPath);
            System.out.println("多文件上传的绝对路径: " + readPath.getAbsolutePath());
            if (!readPath.isDirectory()) {
                readPath.mkdirs();
            }

            File dest = new File(readPath.getAbsolutePath() + File.separator + file.getOriginalFilename());
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                return file.getOriginalFilename() + "上传失败";
            }
        }

        return "上传成功";
    }
}
  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值