Windows版
新建一个properties
# 文件的实体路径
image.path=C:\\Users\\Administrator\\IdeaProjects\\shitang\\img\\
# 待会要获取的IP地址
image.ip=localhost:8080
linux版本
# 文件的实体路径
image.path=/usr/web/shitangdemo/img/
# 待会要获取的IP地址
image.ip=localhost:8000
配置类,让properties的信息获取到这
@Configuration
@PropertySource(value = "file.properties")
public class imgpropertiesConfig implements WebMvcConfigurer {
@Value("${image.path}")
public String path;
private static final String urlPath = "/img/**";
@Value("${image.ip}")
public String ip;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
registry.addResourceHandler(urlPath).addResourceLocations("file:"+path);
}
}
提交Controller
@RestController
@CrossOrigin
public class imgController {
@Autowired
public imgpropertiesConfig config;
@Autowired
public ResponseUtil responseUtil;
@RequestMapping("/img")
public String getLocation()
{
return config.path;
}
@RequestMapping(value = "/addImage",method = RequestMethod.POST)
public Map<String,Object> returnImg(@RequestPart("file") MultipartFile file,@RequestParam("foodname") String foodname)
{
if(file.isEmpty())
{
return responseUtil.fileFail();
}
else
{
System.out.println(config.path);
String filePath = config.path+foodname+".jpg";
File imgfile = new File(filePath);
try{
FileOutputStream stream = new FileOutputStream(imgfile);
byte[] bytes = file.getBytes();
stream.write(bytes);
stream.close();
return responseUtil.fileSuccess(config.ip+"/img/"+foodname+".jpg");
}
catch (Exception e)
{
e.printStackTrace();
return responseUtil.fileFail();
}
}
}
}
|