目录
1.spring boot的静态资源访问
1.1默认静态资源
默认的静态资源目录为:resources/META-INF/resources、resources/public、resources/resources、resources/static。一般用于存放图片、视频、css、js文件
默认的访问静态资源的URL根路径为:/**
所以访问resources/META-INF/resources/baidu1.jpg 的URL为 http://localhost:8080/baidu1.jpg
1.2 Controller高优先级
如果一个Controller的的@RequestMapping定义的访问路径,和静态资源的URL访问路径一样,则返回Controller的内容
2.映射非静态资源路径访问
可以通过配置参数: spring.mvc.static-path-pattern: /uploads/**,
spring:
mvc:
static-path-pattern: /uploads/**
file:
upload-dir: uploads/
修改静态资源的URL根路径。
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 WebConfig implements WebMvcConfigurer {
@Value("${file.upload-dir}")
private String uploadDir;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:" + uploadDir);
}
}
如果没有uploads文件夹,则需要设置创建文件夹
package com.sky.controller.testcontroller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.io.File;
@Component
public class FileUploadDirInitializer implements CommandLineRunner {
@Value("${file.upload-dir}")
private String uploadDir;
@Override
public void run(String... args) throws Exception {
File dir = new File(uploadDir);
if (!dir.exists()) {
dir.mkdirs();
}
}
}
3.springboot的文件上传实现
package com.sky.controller.testcontroller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* @version 1.0
* @auther hkk
*/
@RestController
@Slf4j
public class Uploadfile {
@Value("${file.upload-dir}")
private String uploadDir;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
// 获取原始文件名
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// 创建保存文件的路径
Path path = Paths.get(uploadDir + File.separator + fileName);
Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
// 返回文件访问路径
String fileDownloadUri = "/uploads/" + fileName;
return ResponseEntity.ok(fileDownloadUri);
} catch (IOException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("File upload failed: " + e.getMessage());
}
}
}