21

I have been integrating spring into an application, and have to redo a file upload from forms. I am aware of what Spring MVC has to offer and what I need to do to configure my controllers to be able to upload files. I have read enough tutorials to be able to do this, but what none of these tutorials explain is correct/best practice methods on how/what is to be done to actually handle the file once you have it. Below is some code similar to code found on the Spring MVC Docs on handling file uploads which can be found at
Spring MVC File Upload

In the example below you can see that they show you everything to do to get the file, but they just say Do Something with the bean

I have checked many tutorials and they all seem to get me to this point, but what I really want to know is the best way to handle the file. Once I have a file at this point, what is the best way to save this file to a directory on a server? Can somebody please help me with this? Thanks

public class FileUploadController extends SimpleFormController {

protected ModelAndView onSubmit(
    HttpServletRequest request,
    HttpServletResponse response,
    Object command,
    BindException errors) throws ServletException, IOException {

     // cast the bean
    FileUploadBean bean = (FileUploadBean) command;

     let's see if there's content there
    byte[] file = bean.getFile();
    if (file == null) {
         // hmm, that's strange, the user did not upload anything
    }

    //do something with the bean 
    return super.onSubmit(request, response, command, errors);
}
5
  • 1
    just simply open an outputstream and write the bytes to the stream. FileOutputStram fos = new FileOutputStream("location/on/server/filename"); fos.write(file); fos.close();
    – mhshams
    Commented Aug 26, 2010 at 18:00
  • You do realise that you're following the docs for Spring 2.0, right? Things have moved on a lot in the Spring world since then. I Strongly suggest using 3.0 instead, you'll find many things a lot easier, including file upload.
    – skaffman
    Commented Aug 26, 2010 at 18:48
  • I have read the documentation for Spring 3.0 as well regarding using multipart forms and the documentation for the multipart handling is almost identical to the 2.0 documentation. Commented Aug 26, 2010 at 20:18
  • But you're still using SimpleFormController, which is obsolete and deprecated in Spring 3.
    – skaffman
    Commented Aug 26, 2010 at 20:52
  • correct, I understand, what I was trying to really show was what was in the obSubmit() method, this is not my code. Thank you for the help. Commented Aug 26, 2010 at 21:36

3 Answers 3

20

This is what i prefer while making uploads.I think letting spring to handle file saving, is the best way. Spring does it with its MultipartFile.transferTo(File dest) function.

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

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

@Controller
@RequestMapping("/upload")
public class UploadController {

    @ResponseBody
    @RequestMapping(value = "/save")
    public String handleUpload(
            @RequestParam(value = "file", required = false) MultipartFile multipartFile,
            HttpServletResponse httpServletResponse) {

        String orgName = multipartFile.getOriginalFilename();

        String filePath = "/my_uploads/" + orgName;
        File dest = new File(filePath);
        try {
            multipartFile.transferTo(dest);
        } catch (IllegalStateException e) {
            e.printStackTrace();
            return "File uploaded failed:" + orgName;
        } catch (IOException e) {
            e.printStackTrace();
            return "File uploaded failed:" + orgName;
        }
        return "File uploaded:" + orgName;
    }
}
5
  • To get the base path use request.getServletContext().getRealPath("/")
    – Roberto
    Commented Mar 15, 2016 at 23:41
  • 1
    @Roberto getRealPath("/") returns web content dir. Its not good idea to save files in there. When the application redeploys, saved/uploaded files will be lost. Commented Mar 14, 2017 at 21:04
  • multipartFile.transferTo(dest); gives me IOException. I made sure I have created the required directories. Do you have any idea on what the reason might be?
    – MR AND
    Commented Apr 18, 2017 at 14:33
  • 1
    @AND, investigating exception stack trace might help resolve the issue. Maybe app is not allowed the write to "dest"? Commented Jun 3, 2017 at 17:16
  • I realized that the name of the directory was misspelled. Fixing that resolved my issue.
    – MR AND
    Commented Jun 5, 2017 at 20:15
2

but what none of these tutorials explain is correct/best practice methods on how/what is to be done to actually handle the file once you have it

The best practice depends on what you are trying to do. Usually i use some AOP to post-proccessing the uploaded file. Then you can use FileCopyUtils to store your uploaded file

@Autowired
@Qualifier("commandRepository")
private AbstractRepository<Command, Integer> commandRepository;

protected ModelAndView onSubmit(...) throws ServletException, IOException {
    commandRepository.add(command);
}

AOP is described as follows

@Aspect
public class UploadedFileAspect {

    @After("execution(* br.com.ar.CommandRepository*.add(..))")
    public void storeUploadedFile(JoinPoint joinPoint) {
        Command command = (Command) joinPoint.getArgs()[0];

        byte[] fileAsByte = command.getFile();
        if (fileAsByte != null) {
            try {
                FileCopyUtils.copy(fileAsByte, new File("<SET_UP_TARGET_FILE_RIGHT_HERE>"));
            } catch (IOException e) {
                /**
                  * log errors
                  */
            }
        }

    }

Do not forget enable aspect (update schema to Spring 3.0 if needed) Put on the classpath aspectjrt.jar and aspectjweaver.jar (<SPRING_HOME>/lib/aspectj) and

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                          http://www.springframework.org/schema/aop
                          http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    <aop:aspectj-autoproxy />
    <bean class="br.com.ar.aop.UploadedFileAspect"/>
-1

Use the below controller class for processing the file upload.

@Controller
public class FileUploadController {

  @Autowired
  private FileUploadService uploadService;

  @RequestMapping(value = "/fileUploader", method = RequestMethod.GET)
  public String home() {
    return "fileUploader";
  }

  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  public @ResponseBody List<UploadedFile> upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {

    // Getting uploaded files from the request object
    Map<String, MultipartFile> fileMap = request.getFileMap();

    // Maintain a list to send back the files info. to the client side
    List<UploadedFile> uploadedFiles = new ArrayList<UploadedFile>();

    // Iterate through the map
    for (MultipartFile multipartFile : fileMap.values()) {

      // Save the file to local disk
      saveFileToLocalDisk(multipartFile);

      UploadedFile fileInfo = getUploadedFileInfo(multipartFile);

      // Save the file info to database
      fileInfo = saveFileToDatabase(fileInfo);

      // adding the file info to the list
      uploadedFiles.add(fileInfo);
    }

    return uploadedFiles;
  }

  @RequestMapping(value = {"/listFiles"})
  public String listBooks(Map<String, Object> map) {

    map.put("fileList", uploadService.listFiles());

    return "listFiles";
  }

  @RequestMapping(value = "/getdata/{fileId}", method = RequestMethod.GET)
  public void getFile(HttpServletResponse response, @PathVariable Long fileId) {

    UploadedFile dataFile = uploadService.getFile(fileId);

    File file = new File(dataFile.getLocation(), dataFile.getName());

    try {
      response.setContentType(dataFile.getType());
      response.setHeader("Content-disposition", "attachment; filename=\"" + dataFile.getName() + "\"");

      FileCopyUtils.copy(FileUtils.readFileToByteArray(file), response.getOutputStream());


    } catch (IOException e) {
      e.printStackTrace();
    }
  }


  private void saveFileToLocalDisk(MultipartFile multipartFile) throws IOException, FileNotFoundException {

    String outputFileName = getOutputFilename(multipartFile);

    FileCopyUtils.copy(multipartFile.getBytes(), new FileOutputStream(outputFileName));
  }

  private UploadedFile saveFileToDatabase(UploadedFile uploadedFile) {
    return uploadService.saveFile(uploadedFile);
  }

  private String getOutputFilename(MultipartFile multipartFile) {
    return getDestinationLocation() + multipartFile.getOriginalFilename();
  }

  private UploadedFile getUploadedFileInfo(MultipartFile multipartFile) throws IOException {

    UploadedFile fileInfo = new UploadedFile();
    fileInfo.setName(multipartFile.getOriginalFilename());
    fileInfo.setSize(multipartFile.getSize());
    fileInfo.setType(multipartFile.getContentType());
    fileInfo.setLocation(getDestinationLocation());

    return fileInfo;
  }

  private String getDestinationLocation() {
    return "Drive:/uploaded-files/";
  }
}
1
  • UploadedFile is not defined.
    – MuffinMan
    Commented Nov 6, 2015 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.