Spring MVC将上传的MultipartFile保存到特定文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10847994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 05:08:56  来源:igfitidea点击:

Spring MVC save uploaded MultipartFile to specific folder

springfiletomcatimage-uploading

提问by Alexander

I want to save uploaded images to a specific folder in a Spring 3 MVC application deployed on Tomcat

我想将上传的图像保存到部署在 Tomcat 上的 Spring 3 MVC 应用程序中的特定文件夹

My problem is that I cannot save the uploaded images files to the host where the applciation is running.

我的问题是我无法将上传的图像文件保存到运行应用程序的主机。

Here is what I tried:

这是我尝试过的:

private void saveFile(MultipartFile multipartFile, int id) throws Exception {
    String destination = "/images/" + id + "/"  + multipartFile.getOriginalFilename();
    File file = new File(destination);
    multipartFile.transferTo(file);
}

Result: FileNotFoundException - Yes sure, I do want create this file!?!

结果:FileNotFoundException - 是的,我确实想创建这个文件!?!

I tried it using the context.getRealPathor getResources("destination"), but without any success.

我尝试使用context.getRealPathor getResources("destination"),但没有任何成功。

How can I create a new file in a specific folder of my app with the content of my multipart file?

如何使用我的多部分文件的内容在我的应用程序的特定文件夹中创建一个新文件?

回答by Ravi Maroju

This code will surely help you.

这段代码肯定会帮助你。

String filePath = request.getServletContext().getRealPath("/"); 
multipartFile.transferTo(new File(filePath));

回答by Yuliia Ashomok

Let's create the uploadsdirectory in webapp and save files in webapp/uploads:

让我们在 webapp 中创建uploads目录并将文件保存在webapp/uploads 中

@RestController
public class GreetingController {

    private final static Logger log = LoggerFactory.getLogger(GreetingController.class);

    @Autowired
    private HttpServletRequest request;


    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
        public
        @ResponseBody
        ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
            if (!file.isEmpty()) {
                try {
                    String uploadsDir = "/uploads/";
                    String realPathtoUploads =  request.getServletContext().getRealPath(uploadsDir);
                    if(! new File(realPathtoUploads).exists())
                    {
                        new File(realPathtoUploads).mkdir();
                    }

                    log.info("realPathtoUploads = {}", realPathtoUploads);


                    String orgName = file.getOriginalFilename();
                    String filePath = realPathtoUploads + orgName;
                    File dest = new File(filePath);
                    file.transferTo(dest);

the code
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);

编码
String realPathtoUploads = request.getServletContext().getRealPath(uploadsDir);

returns me next path if I run the app from Idea IDE
C:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\

如果我从 Idea IDE 运行应用程序,则返回下一条路径
C:\Users\Iuliia\IdeaProjects\ENumbersBackend\src\main\webapp\uploads\

and next path if I make .war and run it under Tomcat:
D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\

如果我制作 .war 并在 Tomcat 下运行它,则下一条路径:
D:\Programs_Files\apache-tomcat-8.0.27\webapps\enumbservice-0.2.0\uploads\

My project structure:
enter image description here

我的项目结构:
在此处输入图片说明

回答by Diego Victor de Jesus

You can get the inputSream from multipartfile and copy it to any directory you want.

您可以从 multipartfile 获取 inputSream 并将其复制到您想要的任何目录。

public String write(MultipartFile file, String fileType) throws IOException {
    String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss-"));
    String fileName = date + file.getOriginalFilename();

    // folderPath here is /sismed/temp/exames
    String folderPath = SismedConstants.TEMP_DIR + fileType;
    String filePath = folderPath + "/" + fileName;

    // Copies Spring's multipartfile inputStream to /sismed/temp/exames (absolute path)
    Files.copy(file.getInputStream(), Paths.get(filePath), StandardCopyOption.REPLACE_EXISTING);
    return filePath;
}

This works for both Linux and Windows.

这适用于 Linux 和 Windows。

回答by Marco Schoolenberg

I saw a spring 3 example using xml configuration (note this does not wok for spring 4.2.*): http://www.devmanuals.com/tutorials/java/spring/spring3/mvc/spring3-mvc-upload-file.html`

我看到了一个使用 xml 配置的 spring 3 示例(注意这不适用于 spring 4.2.*):http: //www.devmanuals.com/tutorials/java/spring/spring3/mvc/spring3-mvc-upload-file。 HTML`

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000" />
<property name="uploadTempDir" ref="uploadDirResource" />
</bean>

<bean id="uploadDirResource" class="org.springframework.core.io.FileSystemResource">
<constructor-arg>
<value>C:/test111</value>
</constructor-arg>
</bean>

回答by Laster Liang

String ApplicationPath = 
        ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("");

This is how to get the real path of App in Spring (without using response, session ...)

这就是如何在Spring中获取App的真实路径(不使用响应,会话......)

回答by Vijay

The following worked for me on ubuntu:

以下在 ubuntu 上对我有用:

String filePath = request.getServletContext().getRealPath("/");
File f1 = new File(filePath+"/"+multipartFile.getOriginalFilename());
multipartFile.transferTo(f1);