Spring将上传的文件保存为公共资源

时间:2016-01-18 22:34:31

标签: spring server

将公共图像存储在文件系统上的一般方法是什么? 我在服务器上有一个endpoint来保存文件。但我不明白的是如何让它公开访问,以便我不必为这些公共文件创建端点(我认为这将是不必要的开销)?我需要添加一些单独的文件服务器吗? 我的网络应用程序架构是:

Angular.js client
     |
Node.js client server
     |
Spring backend on separate server

我想要达到的目标是

<img src="localhost:8000/public/images/myImage"/>

我来this回答,但是让端点成为正确的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以将图像保存到任何路径,但对于webroot不是必需的。您可以在显示图像时从该目录中读取图像。

<强> ImageController.java

 package com.expertwebindia;

    import java.io.File;
    import java.io.FileInputStream;

    import javax.servlet.http.HttpServletResponse;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;

    @Controller
    public class ImageController {
        private String path = "E:/uploads/";
        @RequestMapping(value = "/image/display",method=RequestMethod.GET)
        @ResponseBody
        public byte[] helloWorld(@RequestParam String name,HttpServletResponse response)  {
            System.out.println("Show is invoked");
            response.setContentType("image/jpeg");
            File file;
          byte arr[]={};
          try{
                 file = new File(path+name);
                  if(file.isFile()){
                      System.out.println("File is found");
                  }
                  else{
                      name = "no-image.jpg";
                      file = new File(path+name); 
                  }
              arr= new byte[(int)file.length()];
              FileInputStream fis = new FileInputStream(file);
              fis.read(arr,0,arr.length);
          }catch(Exception e){
              System.out.println(e);
          }
          return arr;
        }
    }

在需要显示的JSP中需要将<img>标记放在下面。注意我在这里使用了JSTL标记,因此您需要将JSTL jar添加到WEB-INF / lib并将taglib添加到JSP页面。

<img alt="" src="<c:url value="/image/display?name=${image_name}"/>"/>

Learn more about Spring MVC file upload

答案 1 :(得分:0)

如果要将图像存储在应用程序资源文件夹中,请尝试以下操作:

一个。资源映射(可以访问此文件夹中的所有目录):

<mvc:resources location="/resources/" mapping="/resources/**"/>

B中。在jsp页面中添加:

<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>

<img src="<spring:url value='/resources/profile-pictures/${user.profileImage}'/>" class="img-circle" alt="User Image">

注意:所有上传的图片都会存储在src\main\webapp\resources\profile-pictures目录下。

℃。禁用安全性:

<http pattern="/resources/**" security="none"/>

d。保存图像的方法:

@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);
    //System.out.println(user.toString());
    try {
        if (!file.isEmpty()) {
             BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
             File destination = new File(webappRoot + "/resources/profile-pictures/ProfileImage"+user.getName()+".jpg"); // something like C:/Users/tom/Documents/nameBasedOnSomeId.png
             ImageIO.write(src, "png", destination);
             System.out.println("users profile Pic is stored at "+user.getProfileImage() + "UserPassword :" +user.getPassword());
             user.setProfileImage("ProfileImage"+user.getName()+".jpg");
             userService.update(user);
             System.out.println("Image is stored at "+ user.getProfileImage());
        } 
    } catch (Exception e) {
        System.out.println("Exception occured" + e.getMessage());
        return "redirect:/account/upload?success=false";
    }
    return "redirect:/account/upload?success=true";
}

PS:这不是理想的解决方案,但可用于学习目的。我也在寻找免费的图像存储。我遇到了亚马逊S3,但它需要信用卡,然后有Box,Dropbox。但我发现这个Cloudinary非常有趣。

PPS:您可以看到我的演示应用here