/**
* @param file 上传的文件
* @return 文件的地址
*/
@Override
public String uploadFile(MultipartFile file) throws Exception {
String abPath = getAbPath();
// 这里是上传文件的方法就不贴了,可以自行百度一下,第一个参数是绝对路径 第二个参数是文件
String name = FileUploadUtils.upload(abPath, file);
String domain = getAccessPath();
String url = domain + name;
return url;
}
@SneakyThrows
public String getAccessPath(){
String networkProtocol = "http";
String ip = Inet4Address.getLocalHost().getHostAddress();
String port = environment.getProperty("server.port");
System.out.println(networkProtocol + "://" + ip + ":" + port);
return networkProtocol + "://" + ip + ":" + port;
}
/**
* 在开发测试模式时,得到的地址为:{项目跟目录}/target/classes/images/upload/
* 在打包成jar正式发布时,得到的地址为:{发布jar包目录}/images/upload/
*/
@SneakyThrows
public static String getAbPath(){
//获取跟目录(绝对路径)
String decoderURL= URLDecoder.decode(ResourceUtils.getURL("classpath:").getPath(),"utf-8");
File path = new File(decoderURL);
if (!path.exists()){
path = new File("");
}
//如果上传目录为/images/upload/,则可以如下获取:
File upload = new File(path.getAbsolutePath(),"/images/upload/");
if(!upload.exists()){
upload.mkdirs();
}
String abPath = upload.getAbsolutePath();
// 如果是windows环境 将反斜杠替换为正斜杠
abPath = abPath.replace("\\","/");
return abPath;
}
获取图片路径配置
/**
* 通用映射配置
*
*/
@Configuration
@Data
public class ResourcesConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/** 本地文件上传路径 */
String abPath = FileUploadUtils.getAbPath();
registry.addResourceHandler("/**").addResourceLocations("file:" + abPath + "/");
}
}
配置完成后就可以通过ip+端口+ 相对路径 就可以访问图片或者文件
网友评论