大家好,又见面了,我是你们的朋友全栈君。
jar打包方式不支持将文件动态写入文件,这时需要通过映射的方式将文件上传到映射某一个文件夹,通过映射获取文件,在页面显示。
file:
#服务器地址
uploadurl: "/u01/upload/images/"
#本地地址
#localurl: "D:/springbootFile/upload/images/"
@Value("${file.uploadurl}")
private String uploadPath;
@PostMapping("/fileUpload")
@ApiOperation(value = "上传下载图片")
public JsonResult filesUpload(@RequestParam("filesName") MultipartFile file,
@RequestParam("mmsi") String mmsi) throws IOException {
JsonResult result = new JsonResult();
//如果文件夹不存在,创建
File fileP = new File(uploadPath);
if (!fileP.isDirectory()) {
//递归生成文件夹
fileP.mkdirs();
}
String fileName = "";
if(file.getOriginalFilename().endsWith(".jpg")){
fileName =String.format("%s.jpg",System.currentTimeMillis());
}else if(file.getOriginalFilename().endsWith(".png")){
fileName =String.format("%s.jpg",System.currentTimeMillis());
}else if(file.getOriginalFilename().endsWith(".jpeg")){
fileName =String.format("%s.jpeg",System.currentTimeMillis());
}else if(file.getOriginalFilename().endsWith(".bmp")){
fileName =String.format("%s.bmp",System.currentTimeMillis());
}else{
result.setSuccess(false);
result.setCode("0");
result.setMessage("图片格式不正确!,使用.jpg/.png/.bpm/.jpeg后缀的图片");
return result;
}
file.transferTo(new File(fileP,fileName));
//数据库存入地址
cxShipDetailService.insertShipPic(mmsi,uploadPath+fileName,fileName);
result.setSuccess(true);
result.setCode("1");
result.setMessage("上传图片成功!");
return result;
}
上传功能就到此结束了。那么肯定会问,上传了怎么获取图片呢?很简单,通过地址映射就可以获取了。
import org.springframework.beans.factory.annotation.Value;
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 FileConfig implements WebMvcConfigurer {
@Value("${file.uploadurl}")
private String fileUrl;
public void addResourceHandlers(ResourceHandlerRegistry register){
register.addResourceHandler("/images/**").addResourceLocations("file:"+fileUrl);
}
}
方式二:除了配置类还有另一种方式,那就是直接在配置文件配置spring的资源文件地址:
spring:
mvc:
static-path-pattern: /image/**
resources:
#本地地址
static-locations: file:D://test/
#linux服务器地址
#static-locations: file:/u01/upload/images/
但是通过方式二有弊端,如果配置了swagger你会发现不能打开swagger了,是因为默认资源位置已被映射,无法找到, 所以需要通过配置类指定资源位置
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 WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
建议直接使用第一种方式!
效果:这里的imags对应配置类里面的获取地址。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/145073.html原文链接:https://javaforall.cn