Alexander
Alexander

Reputation: 7238

Spring MVC save uploaded MultipartFile to specific folder

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

My problem is that I cannot save the uploaded images files to the host where the appliciation 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!?!

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

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

Upvotes: 45

Views: 120207

Answers (6)

Diego Victor de Jesus
Diego Victor de Jesus

Reputation: 3003

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

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 + File.separator + 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.

Upvotes: 15

Vijay
Vijay

Reputation: 313

The following worked for me on ubuntu:

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

Upvotes: 0

user7152981
user7152981

Reputation:

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

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

Upvotes: 0

Marco Schoolenberg
Marco Schoolenberg

Reputation: 743

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 `

<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>

Upvotes: 1

Yuliia Ashomok
Yuliia Ashomok

Reputation: 8598

Let's create the uploads directory in webapp and save files in 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);

returns me next path if I run the app from 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\

My project structure:
enter image description here

Upvotes: 20

Ravi Maroju
Ravi Maroju

Reputation: 667

This code will surely help you.

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

Upvotes: 44

Related Questions