问题描述:SpringBoot项目中需要上传文件到当前服务器的磁盘(即物理地址),返回可访问的路径给前端。前端利用路径显示文件内容。
开发环境:SpringBoot2.0以上、JDK 1.8
1.在springboot中加入下面代码
@Value("${file.uploadFolder}")
private String uploadFolder;
@Bean
MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setLocation(uploadFolder);
return factory.createMultipartConfig();
}
自定义MVC文件映射
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${smas.captrue.image.path}")
private String captureImagePath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/").allowedOrigins("").allowCredentials(true).allowedMethods("").maxAge(3600);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder + captureImagePath);
}
}
文件上传
@RequestMapping(path = "/files")
@RestController
public class FileController {
@Value("${smas.captrue.image.path}")
private String captureImagePath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Value("${file.uri}")
private String uri;
@RequestMapping(value = "/upload")
public FileVo emailUpload(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> files = multipartRequest.getFileMap();
String path_deposit = uploadFolder + captureImagePath;
List<String> urls = new ArrayList<>();
for (Map.Entry<String, MultipartFile> entry : files.entrySet()) {
try {
String fileName = entry.getValue().getOriginalFilename();
FileHandleUtil.upload(entry.getValue().getInputStream(), path_deposit, fileName);
urls.add(FileHandleUtil.getServerIPPort(request) + File.separator + uri + fileName);
} catch (IOException e) {
throw new SmasException("文件读取异常");
}
}
FileVo fileVo = new FileVo();
fileVo.setErrno("0");
fileVo.setData(urls);
return fileVo;
}
}
在application.properties中增加以下配置
图片临时路径#单个数据的大小spring.servlet.multipart.maxFileSize=10Mb#总数据的大小spring.servlet.multipart.maxRequestSize=10Mb#文件上传后存储路径:D:\home\capture\5*.jpg(具体配置如下)#访问Url:http://ip:port/smas/upload/#文件上传目录(window是d/e/f盘, linux是/)(注意Linux和Windows上的目录结构不同)#file.uploadFolder=/file.uploadFolder=d://# 设备截图文件保存路径(文件存在具体的文件夹的路径)smas.captrue.image.path=home/capture/#静态资源对外暴露的访问路径(访问图片的路径)file.staticAccessPath=/upload/*#浏览器访问file.uri=smas/upload/
文件处理工具类
public class FileHandleUtil {
/**
- 上传单个文件
- @param inputStream 文件流
- @param path 文件路径,如:image/
- @param filename 文件名,如:test.jpg
- @return 成功:上传后的文件访问路径,失败返回:null
*/
public static String upload(InputStream inputStream, String path, String filename) {
//创建文件夹
createDirIfNotExists(path);
//存文件
File uploadFile = new File(path, filename);
try {
FileUtils.copyInputStreamToFile(inputStream, uploadFile);
} catch (IOException e) {
throw new SmasException("文件上传失败!");
}
return uploadFile.getPath();
}
/**
- 创建文件夹路径
*/
private static void createDirIfNotExists(String path) {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
}
/**
- 删除文件
- @param path 文件访问的路径upload开始 如:/upload/image/test.jpg
- @return true 删除成功;false 删除失败
*/
public static boolean delete(String path) {
File file = new File(path);
return file.exists() == true ? file.delete() : true;
}
/**
- 获取服务部署根路径 http:// + ip + port
- @param request
- @return
*/
public static String getServerIPPort(HttpServletRequest request) {
//+ ":" + request.getServerPort()
return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
}
}
网友评论