WebMvcConfigurer配置
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@SneakyThrows
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//和页面有关的静态目录都放在项目的static目录下
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("/Image/**").addResourceLocations("file:Image/");
registry.addResourceHandler("/upload/**").addResourceLocations("file:upload/");
}
}
/**
* 临时上传存储空间
* @author zhangshichuan
* @date 2021/2/26 11:05
*/
@Configuration
public class UploadConfig {
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setLocation(System.getProperty("user.dir")+"/uploadimg/");
return factory.createMultipartConfig();
}
}
@RequestMapping("uploadimg")
@ResponseBody
public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) {
Map<String, Object> map = new HashMap();
Map<String,Object> map2 = new HashMap<>();
Calendar calendar = Calendar.getInstance();
Date date =calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String stringDate = sdf.format(date);
String newName = UUID.randomUUID().toString().replace("-","");
System.out.println("newName:"+newName);
try {
//在jar包的同级目录下创建image文件夹
String name = file.getOriginalFilename();
String fileName = newName +name.substring(name.lastIndexOf("."), name.length());
String path = System.getProperty("user.dir")+"/upload/"+stringDate+"/";
System.out.println("path:"+path);
File filePath = new File(path+fileName);
System.out.println("filePath:"+filePath);
if (!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
}
FileCopyUtils.copy(file.getInputStream(),new FileOutputStream(filePath));
String imgName = "/upload/"+stringDate+"/"+fileName;
/*//得到协议名 例如:https://localhost:8090/
String PP =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/static/upload/";*/
map.put("code", 0);
map.put("msg", "上传成功");
/*map2.put("src",PP+name);*/
map2.put("src",imgName);
map2.put("title",file.getOriginalFilename());
map.put("data",map2);
}catch (Exception e){
System.out.println(e);
map.put("code", 1);
map.put("msg", e);
map2.put("src", "");
map2.put("title","");
map.put("data", "");
}
return map;
}