Spring Boot 本地文件上传及提供HTTP访问服务

简介

服务端接收上传的目的是提供文件的访问服务,那么对于SpringBoot而言,可以提供文件访问的静态资源目录:

  • classpath:/META-INF/resources/ ,
  • classpath:/static/ ,
  • classpath:/public/ ,
  • classpath:/resources/

上传目录自定义配置

Spring boot 为我们提供了使用spring.web.resources.static-locations配置自定义静态文件的位置。

web:
  upload-path: F:\\images
server:
  #端口号
  port: 8888
spring:
  web:
    resources:
      static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
  • 配置web.upload-path为与项目代码分离的静态资源路径,即:文件上传保存根路径
  • 配置spring.web.resources.static-locations,除了带上Spring Boot默认的静态资源路径之外,加上file:${web.upload-path}指向外部的文件资源上传路径。该路径下的静态资源可以直接对外提供HTTP访问服务。即,在F:\\images文件下的资源都可以通过路径直接打开。如:有一个1.jpg图片在浏览器中直接可以访问http://localhost:8888/1.jpg看到图片

文件上传实现

前端

 <body>
  <h2>单文件上传h2>
  <form action="http://127.0.0.1:8888/fileUpload/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="">
    <input type="submit" value="上传">
  form>
     
  <h2>多文件上传h2>
  <form action="http://127.0.0.1:8888/fileUpload/filesUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="files" id="">
    <input type="file" name="files" id="">
    <input type="file" name="files" id="">
    <input type="submit" value="上传">
  form>
body>

单文件上传

package com.liu.kaptcha.controller;

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

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/fileUpload")
public class FileUploadController {

    @Value("${web.upload-path}")
    private String uploadPath;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest request) {

        // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
        // 比如:/2022/03/16/cf13891e-4b95-4000-81eb-b6d70ae44930.png
        String format = sdf.format(new Date());

        File folder = new File(uploadPath+"/"+format);

        if (!folder.isDirectory()) {
            folder.mkdirs();
        }

        // 对上传的文件重命名,避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());

        try {
            // 文件保存
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径  http://localhost:8888/2022/03/16/85e4fcac-c903-4a7d-bdce-b155b4354402.jpeg
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/"+format+ newName;
            return filePath;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}

多文件上传

@PostMapping("/filesUpload")
public String filesUpload(@RequestParam("files") MultipartFile[] uploadFiles, HttpServletRequest request) {

    // 在 uploadPath 文件夹中通过日期对上传的文件归类保存
    // 比如:/2022/03/16/cf13891e-4b95-4000-81eb-b6d70ae44930.png
    String format = sdf.format(new Date());

    File folder = new File(uploadPath+"/"+format);

    if (!folder.isDirectory()) {
        folder.mkdirs();
    }

    String str="";

    for(MultipartFile uploadFile : uploadFiles){
        // 对上传的文件重命名,避免文件重名
        String oldName = uploadFile.getOriginalFilename();
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."), oldName.length());

        try {
            // 文件保存
            uploadFile.transferTo(new File(folder, newName));

            // 返回上传文件的访问路径  http://localhost:2000//spring-master/85e4fcac-c903-4a7d-bdce-b155b4354402.jpeg
            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+"/"+format+ newName;
            str += filePath+",";
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return str;
}

你可能感兴趣的:(java,spring,boot,http,java)