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



我按照这种方法成功上传到"/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";
}

这工作得很好,试试看....它将返回整个路径

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

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

是的,使用 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";
}

您可以参考此存储库中的完整源代码。

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

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

最新更新