图片上传到电脑磁盘并在中tomcat配置虚拟路径
问题: 文件上传时一般生成临时文件来保存目录,这个临时文件在tomcat下,修改代码或重启tomcat临时文件下保存的文件或图片都会消失不见了,但是若保存在本地磁盘上,用
文章图片
2、script代码
页面效果:
没有后台之前会提示“上传失败”,但还是会显示图片,同时页面左下角,会提示“上传失败重试”,我这里是上传成功了
文章图片
3、后端代码
@RequestMapping(value="https://www.it610.com/text" ,method=RequestMethod.Post)
@ResponseBody
public Map text(@RequestParam("file") MultipartFile file,HttpServletRequest request,HttpServletResponse){
response.setContType("text/html;
charset=utf-8");
String tempPath="G:/images/upload/";
//存到本地
File tmpFile=new File(tempPath);
if(!tmpFile.exists()){
//创建临时目录
tmpFile.mkdir();
}
Map map =new HashMap<>();
//获取原始文件名
String fileName=file.getOriginalFilename();
String houzuiming=fileName.substring(fileName.lastIndexOf(".")+1);
//后缀名
//新文件名
String newFileName=UUID.randomUUId()+"."+houzuiming;
//这里也可用随机数作新文件名
try{
FileOutputStream fos=new FileOutputStream(tempPath+newFileName);
InputStream in=file.getInputStream();
int b=0;
while((b=in.read()) != -1){
fos.write(b);
}
fos.close();
in.close();
map.put("code",0);
//上传成功
map.put("image","/imagespath/"+newFileName);
//server.xml中的虚拟路径
}catch(Exception e){
map.put("code",1);
e.printStackTrace();
}
return map;
}
4、tomcat的server.xml中配置虚拟路径(重要)
5、前台显示
文章图片
最后,把项目重启就可以了
页面效果:
【图片上传到电脑磁盘并在中tomcat配置虚拟路径】
文章图片