使用Spring MVC将图像上传到/ webapp / resources / images目录

时间:2016-07-15 17:44:53

标签: spring spring-mvc

我按照这种方法成功上传到"/var/www/java/Football/src/main/webapp/resources/images"文件夹但是这里我需要指定完整路径,现在问题是直接获取根路径,就像"webapp/resources/images"无需指定完整路径,如何获得根路径?

@RequestMapping(value="/saveDeal",method=RequestMethod.POST)
public String saveDeal(@ModelAttribute("saveDeal") Deal deal,BindingResult result,@RequestParam("couponCode") MultipartFile file,HttpServletRequest request){

    if(!file.isEmpty()){
        try{
            byte[] bytes=file.getBytes();
            System.out.println("Byte Data :"+bytes);
            String fileName=file.getOriginalFilename();
        File newFile = new File("/var/www/java/Football/src/main/webapp/resources/images");

           if (!newFile.exists()){
                newFile.mkdirs();

            }
            File serverFile = new File(newFile.getAbsolutePath()+File.separator+fileName);
            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();


        }catch(Exception e){
            e.printStackTrace();
        }
    }

    return "redirect:viewDeals.html";
}

3 个答案:

答案 0 :(得分:0)

是的,请使用ServletContext#getRealPath()

尝试将图像存储在" src / main / webapp / resources / profile-pictures":

@RequestMapping(value="/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("imageFile") MultipartFile file, Principal principal) {

    String webappRoot = servletContext.getRealPath("/");
    String LoggedInUser = principal.getName();
    User user = userService.findLoggedInUser(LoggedInUser);
    try {
        if (!file.isEmpty()) {
             BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
             //Images will be stored under "src/main/webapp/resources/profile-pictures"
             File destination = new File(webappRoot + "/resources/profile-pictures/ProfileImage"+user.getName()+".jpg"); 
             ImageIO.write(src, "png", destination);
        } 
    } catch (Exception e) {
        System.out.println("Exception occured" + e.getMessage());
        return "redirect:/account/upload?success=false";
    }
    return "redirect:/account/upload?success=true";
}

您可以参考此Repository中的完整源代码。

答案 1 :(得分:0)

我想知道你对' root'的意思。路径。作为一个servlet,您不知道您的上下文是什么,在什么应用程序服务器中,以及您是否正在运行爆炸或在战争(或EAR)中。 例如,运行代码的人可能已将其编译在JAR中,JAR打包在WAR中,该WAR打包在EAR中。然后没有真正的根源'你的(已编译的)java文件,如果有(如果它在磁盘上爆炸),它仍然是只读的。

所以我不认为这会有用。 您需要定义一个存储文件的目录(可能是可配置的)。 让它由FileResource注入,然后配置必须注意定义一个合适的位置。在Unix上,在Windows上可能是/var/user/JavaTempUser/uploads,可能是e:\uploads。哎呀,它甚至可能是JavaO或者旧的东西。 作为一名java程序员,你应该知道你不知道将运行什么操作系统(因此文件抽象)。

答案 2 :(得分:0)

这样可以正常试用....它将返回整个路径

String filePath = "/uploads/filename";

    // get absolute path of the application
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");

OR

String filepath = "/uploads/" + "tenant/" + tenant + "/project/"
                + projectId + "/task/" + taskId;
        String realPathtoFetch = request.getServletContext().getRealPath(
                filepath);
相关问题