图片上传到电脑磁盘并在中tomcat配置虚拟路径

问题:

文件上传时一般生成临时文件来保存目录,这个临时文件在tomcat下,修改代码或重启tomcat临时文件下保存的文件或图片都会消失不见了,但是若保存在本地磁盘上,用标签中的src直接访问本地图片路径的话,会使图片破裂,显示不出来

解决:

把文件存储在本地,并且在tomcat里面的server.xml配置虚拟路径

具体代码:

1、html代码(layui前端框架,可参考layui官方文档)

layui文件上传:https://www.layui.com/doc/modules/upload.html

......

......

页面效果:

2、script代码

页面效果:

没有后台之前会提示“上传失败”,但还是会显示图片,同时页面左下角,会提示“上传失败重试”,我这里是上传成功了

图片上传到电脑磁盘并在中tomcat配置虚拟路径_第1张图片

3、后端代码

@RequestMapping(value="/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配置虚拟路径_第2张图片

你可能感兴趣的:(图片上传到电脑磁盘并在中tomcat配置虚拟路径)