JAVA上传图片,为什么图片打不开?要等很久

图片描述

@RequestMapping(value="/uploadImage",method = RequestMethod.POST)
    public void uploadImage(@RequestParam("file") MultipartFile file,PrintWriter pw,ModelMap modelMap,HttpServletRequest req) throws IOException {
        String type = file.getOriginalFilename().split("\\.")[1].toLowerCase();  
        String t=Thread.currentThread().getContextClassLoader().getResource("").getPath(); 
        int num=t.indexOf(".metadata");
        String path=t.substring(1,num).replace('/', '\\')+"project001\\WebContent\\static\\admin\\common\\upload\\";
        
        String fileName = "logo"+new Date().getTime()+"."+type;
        if(type.equals("png") || type.equals("jpg") || type.equals("gif") || type.equals("jpeg")){
            File f = new File(path+fileName);
            FileOutputStream out = new FileOutputStream(f);
            out.write(file.getBytes());
            modelMap.put("msg", "上传成功");
        }else{
            modelMap.put("msg", "上传失败,仅支持png,jpg,gif,jpeg格式文件.");
        }
        
        pw.print("{\"msg\":\"上传成功\",\"url\":\""+getBasePath(req)+"static/admin/common/upload/"+fileName+"\"}");
        
    }

这是我的代码。、
要刷新eclipse的项目名才能显示图片在页面上。。有什么办法解决吗?

阅读 5.5k
3 个回答

我觉得可以试试FileOutputStream out = new FileOutputStream(f); 把这个流flush and close一下

我用spring boot rest方式测试其实和close应该没什么关系,从要等很久和刷新eclipse之后能查看,应该是这个文件上传成功只保存在了eclipse项目本地,等待时间就是重新部署的问题了。

新手上路,请多包涵

close就行了

强烈建议使用如下方式输出图片。
import org.apache.commons.io.FileUtils;
FileUtils.writeByteArrayToFile(new File(path+fileName),file.getBytes());
你无需再去关心输出流的关闭刷新,性能上也可靠。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题