简体   繁体   English

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

[英]Saving file to resource directory using Spring

I have this project structure: 我有这个项目结构:


/webapp
  /res
    /img
      /profile.jpg
  /WEB-INF

And I need to save file to res/img/ directory. 我需要将文件保存到res/img/目录。 This time I have this code: 这次我有这个代码:


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();
    }

But it saving files to user.dir directory, which is ~/Work/Tomcat/bin/ . 但它将文件保存到user.dir目录,即~/Work/Tomcat/bin/ So how I can upload files to res directory? 那么如何将文件上传到res目录?

You shouldn't really be uploading files there. 你不应该真的在那里上传文件。

If you are using a war, redeploying will delete them. 如果您正在使用战争,重新部署将删除它们。 If they are intended to be temporary then use an os assigned temporary location. 如果它们是临时的,那么使用os分配的临时位置。

If you intend to publish them afterwards then choose a location in which to store the files on your server, make this location known to the application and save and load files from the location. 如果您打算在之后发布它们,请选择在服务器上存储文件的位置,使应用程序知道此位置并从该位置保存和加载文件。

If you are trying to replace resources dynamically such as an image which is referenced in the html or css templates, then consider publishing the external location separately, you can use mvc:resources for this eg: 如果您尝试动态替换资源(例如html或css模板中引用的图像),那么考虑单独发布外部位置,您可以使用mvc:resources来实现此目的:

<mvc:resources mapping="/images/**" location="file:/absolute/path/to/image/dir"/>

and you would save your files to that location. 并且您将文件保存到该位置。 This will make it more permanent between deployments. 这将使部署之间更加永久。

To save an image to that location using your code you will need to add this into your bean definition (assuming you are using xml configuration without annotations): 要使用代码将图像保存到该位置,您需要将其添加到bean定义中(假设您使用的是没有注释的xml配置):

<property name="imagesFolder" value="/absolute/path/to/image/dir"/>

and keeping your code as similar as possible change it to: 并保持您的代码尽可能相似,将其更改为:

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();
}

Please bear in mind that you need to change /absolute/path/to/image/dir to an actual path that exists, also I would recommend to look at the Spring Resources documentation for a better way to deal with files and resources. 请记住,您需要将/ absolute / path / to / image / dir更改为存在的实际路径,我还建议您查看Spring Resources文档以获得更好的方法来处理文件和资源。

Please refer FileUploadController from here to save file to the specified directory. 请从此处参考FileUploadController以将文件保存到指定目录。

public String fileUpload(UploadedFile uploadedFile) {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    MultipartFile file = uploadedFile.getFile();

    String rootPath = System.getProperty("user.dir");
    File dir = new File(rootPath + File.separator + "webapp"+File.separator+"res"+File.separator+"img");
    if (!dir.exists())
        dir.mkdirs();
    String fileName = file.getOriginalFilename();
    File serverFile = new File(dir.getAbsolutePath() + File.separator + 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM