上传图片后提供一个可静态访问图片的地址(http://+ip+":"+port+/+"file"+/+图片名称)
配置
package com.zxy.dpp.common.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.io.File;
import java.nio.charset.Charset;
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
//上传的图片在D盘下的downLoad目录下,访问路径如:http://localhost:8899/downLoad/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
//file作用 指定文件传输协议 获取电脑文件一般都是file
registry.addResourceHandler("/file/**").addResourceLocations("file:"+System.getProperty("user.dir")+ File.separator+"dpp"+File.separator+"img"+File.separator);
super.addResourceHandlers(registry);
}
}
接口代码
@RestController
public class CommonFileController {
@ApiOperation("用于富媒体图片上传")
@RequestMapping(value = "/file/imgUpload", method = POST, consumes = ALL_VALUE)
// @SkipLogin
public JsonResponse imgUpload(@RequestPart(name = "file") MultipartFile file,
HttpServletRequest request,HttpServletResponse response) {
//文件原名称
String oldFilename = file.getOriginalFilename();
if(!isImageFile(oldFilename)){
return JsonResponse.fail("请上传jpg, jpeg, png, bmp类图片");
}
//图片名后缀:.jpg、.png
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
//uuid
String uuid = UUID.randomUUID().toString();
//文件新名称
String newFileName = uuid + suffix;
String uploadBasePath = System.getProperty("user.dir")+File.separator+"dpp"+File.separator+"img"+File.separator;
//创建保存上传文件的文件夹
File folder = new File(uploadBasePath + newFileName);
if (!folder.getParentFile().exists()) {
folder.getParentFile().mkdirs();
}
//文件写入到该文件夹下
file.transferTo(folder);
//获得本机Ip(获取的是服务器的Ip)
InetAddress inetAddress = InetAddress.getLocalHost();
String ip = inetAddress.getHostAddress();
String fileDownloadUrl = "";
//返回保存的url,根据url可以进行文件查看或者下载
fileDownloadUrl = "http" + "://" + ip + ":" + request.getServerPort() + "/file/" + newFileName;
// 在这里可以把路径url存到数据库
//Entity entity = new Entity()
//entity.setUrl(fileDownloadUrl);
//返回保存的url
return new JsonResponse(fileDownloadUrl);
}
}