application.yml
#上传文件的路径和映射地址
#本地存放路径
localFileUrl: D:\down
#映射的网络url
mappingFileUrl: /static/
#ip访问本地文件
hostFileUrl: http://localhost:8092/static/
MyWebAppConfiguration
package com.cei.xyd_cz.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.cei.xyd_cz.Interceptor.XYDInterceptor;
@Configuration
public class MyWebAppConfiguration extends WebMvcConfigurerAdapter {
@Value("${localFileUrl}")
private String localFileUrl;//本地存放的文件路径 例如:E:\down
@Value("${mappingFileUrl}")
private String mappingFileUrl;//映射的虚拟网络地址 供页面连接访问的url
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(mappingFileUrl+"**").addResourceLocations("file:"+localFileUrl+"/");
}
}
接口
Result返回类型是我自己封装的,自己换自己的
@Value("${localFileUrl}")
private String path;
@Value("${hostFileUrl}")
private String hostPath;
/**
* 产品上传Logo
*
* @param file
* @return
* @throws FileNotFoundException
*/
@PostMapping("/uploadProductFile")
@ResponseBody
public Result uploadProductFile(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
Result res = new Result();
Map<String, Object> map = new HashMap<>();
try {
String dateName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
String fileName = file.getOriginalFilename();
String suffixName = fileName.substring(fileName.lastIndexOf("."));
String filePath = path + "/";
// fileName = dateName + suffixName;
fileName = dateName + "-" + fileName;
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
map.put("filePath", hostPath + fileName);
return ResultGenerator.genSuccessResult(map);
} catch (IOException e) {
System.out.println(e);
}
return ResultGenerator.genFailResult("上传失败");
} catch (Exception e) {
return ResultGenerator.genFailResult(e.getMessage());
}
}
部署的时候别忘了改下application的配置地址,改成线上地址
接口最后拼的filepath就是实际链接地址,直接点就能取到文件,存到库里返给前台看实际业务需求