使用Spring将文件保存到资源目录

Pet*_*ila 4 java spring tomcat

我有这个项目结构:


/webapp
  /res
    /img
      /profile.jpg
  /WEB-INF
Run Code Online (Sandbox Code Playgroud)

我需要将文件保存到res/img/目录.这次我有这个代码:


public String fileUpload(UploadedFile uploadedFile) {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        MultipartFile file = uploadedFile.getFile();
        String fileName = file.getOriginalFilename();
        File newFile = new File("/res/img/" + fileName);

        try {
            inputStream = file.getInputStream();

            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            outputStream = new FileOutputStream(newFile);
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, read);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFile.getAbsolutePath();
    }
Run Code Online (Sandbox Code Playgroud)

但它将文件保存到user.dir目录,这是~/Work/Tomcat/bin/.那么如何将文件上传到res目录呢?

Ned*_*Ned 10

你不应该真的在那里上传文件.

如果您正在使用战争,重新部署将删除它们.如果它们是临时的,那么使用os分配的临时位置.

如果您打算在之后发布它们,请选择在服务器上存储文件的位置,使应用程序知道此位置并从该位置保存和加载文件.

如果您尝试动态替换资源(例如html或css模板中引用的图像),那么考虑单独发布外部位置,您可以使用mvc:resources来实现此目的:

<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir"/>
Run Code Online (Sandbox Code Playgroud)

并且您将文件保存到该位置.这将使部署之间更加永久.

要使用代码将图像保存到该位置,您需要将其添加到bean定义中(假设您使用的是没有注释的xml配置):

<property name="imagesFolder" value="/absolute/path/to/image/dir"/>
Run Code Online (Sandbox Code Playgroud)

并保持您的代码尽可能相似,将其更改为:

private String imagesFolder;
public void setImagesFolder(String imagesFolder) {
    this.imagesFolder = imagesFolder;
}
public String fileUpload(UploadedFile uploadedFile) {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    MultipartFile file = uploadedFile.getFile();
    String fileName = file.getOriginalFilename();
    File newFile = new File(imagesFolder + fileName);

    try {
        inputStream = file.getInputStream();

        if (!newFile.exists()) {
            newFile.createNewFile();
        }
        outputStream = new FileOutputStream(newFile);
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return newFile.getAbsolutePath();
}
Run Code Online (Sandbox Code Playgroud)

请记住,您需要将/ absolute/path/to/image/dir更改为存在的实际路径,我还建议您查看Spring Resources文档以获得更好的方法来处理文件和资源.