web前端上传图片到Java后端,并保存到本地
application.yml中的配置图片存储路径:imagesPath为图片保存到本地的磁盘路径,staticPath为ip地址访问虚拟路径
编写图片上传配置类
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.servlet.MultipartConfigElement;
//上传配置类
// 图片放到 /C:fileUpload/后,从磁盘读取的图片数据scr将会变成images/picturename.jpg的格式
@Configuration
public class WebAppConfig extends WebMvcConfigurationSupport {
/**
* 在配置文件中配置的文件保存路径
*/
@Value("${cbs.imagesPath}")
private String mImagesPath;
@Value("${cbs.staticPath}")
private String staticPath;
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
// 配置上传文件的目录
factory.setLocation(mImagesPath);
//文件最大KB,MB
factory.setMaxFileSize("1024MB");
//设置总上传数据总大小
factory.setMaxRequestSize("1024MB");
return factory.createMultipartConfig();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticPath).addResourceLocations("file:"+mImagesPath);
// TODO Auto-generated method stub
System.out.print("2.上传配置类mImagesPath=="+mImagesPath+"\n");
// super.addResourceHandlers(registry);
}
}
controller层图片上传方法接口:
/**
* 上传图片
* @param file
* @return
*/
@RequestMapping(value = "/uploadFile")
@ResponseBody // 参数:(图片名称,图片(不进行特殊处理))前端统一放到file中,传给后端
public JsonResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
String url = null;
int update = 0;
BaseUser user = SessionUtil.getUser();
//判断文件是否为空
if (file.isEmpty()) {
return new JsonResult(false, "上传文件不能为空");
}
// 获取文件名
String fileName = file.getOriginalFilename();
fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
//加个时间戳,尽量避免文件名称重复
String path = "C:/fileUpload/" + fileName;
//创建文件路径
File dest = new File(path);
//判断文件是否已经存在q
if (dest.exists()) {
return new JsonResult(false, "文件已经存在");
}
//判断文件父目录是否存在
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdir();
}
try {
//上传文件
file.transferTo(dest); //保存文件
String url = "http://183.121.136.142:8087" + "/file/image/" + fileName;//外部访问路径,对应本地的c:/fileupload
} catch (IOException e) {
return new JsonResult(false, "上传失败");
}
return new JsonResult(update>0,update>0?"上传图片成功":"上传图片失败");
}