springboot,文件上传1
application.properties
#设置POST提交的最大值,不限制 spring.servlet.multipart.max-file-size=10MB spring.servlet.multipart.max-request-size=10MB #将项静态目资源路径映射到系统资源路径下(确保http://localhost:8080/1.png可访问) #spring.web.resources.static-locations=file:d:/uploads # 文件上传路径 file.uploadFolder=D:/uploads/ #log4j配置-------------------------- logging.config=classpath:log4j2.xml
Upload.java
package com.example.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
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.util.List;
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/upload/")
public class Upload {
// 文件上传路径,从配置项获取
@Value("${file.uploadFolder}")
private String basePath;
// 简单接口,方便测试
@PostMapping("hello")
public String test1(){
return "hello";
}
// 接收文件夹(实际为文件,但是能获取到相对路径及文件名)
@PostMapping("uploadFolder")
@ResponseBody
public String uploadFileFolder(@RequestParam("file") MultipartFile[] files) {
log.info("uploadFolder 被调用");
for (MultipartFile file : files) {
log.info("file.getOriginalFilename() = {}",file.getOriginalFilename());//飞机/3.jpg或飞机/31b.jpg等
log.info("file.getName() = {}",file.getName());
log.info("file.getResource() = {}",file.getResource());
log.info("file.getContentType() = {}",file.getContentType());
log.info("file.getSize() = {}",file.getSize());
// 目录不会自动创建,否则会异常
File destinationFile = new File(basePath + file.getOriginalFilename());
try {
FileCopyUtils.copy(file.getBytes(), destinationFile);
log.info("上传成功 destinationFile = {}",destinationFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return "333";
}
}
执行结果

访问路径
package com.example.demo.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Slf4j
@Configuration
public class ProviderMvcConfig implements WebMvcConfigurer {
/**
* 设置文件虚拟路径映射
* 访问路径:
* http://localhost:8080/upload/files/1.png
* http://localhost:8080/1.png
* */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/files/**").addResourceLocations("file:d:/uploads/");//这儿必须在尾部加/
}
}
http://localhost:8080/upload/files/1.png
http://localhost:8080/1.png

浙公网安备 33010602011771号