0

I wish to upload a file using a Spring MVC based REST API. The API will be a typical Java web app and will act as the backend.

The frontend will be a HTML web app that uses JQuery.

I want to show an upload box using which user can select the file to be uploaded. Now this file has to be passed as parameter to the API so that it can be stored by the API.

These are my questions--

(1) In the service class I am thinking of passing a File object as parameter. However how do I connect the file being uploaded with this file object input parameter? Am I correct in thinking like this, or is there some other approach to do this?

(2) In case my suggested method works and there are other ways also of achieving the same thing, which method would you recommend for such a scenario- if you can point me to a tutorial/guide/how to explaining how to upload a file as per above scenario, or explain it yourself-- that would be very helpful for me.

1 Answer 1

0

You shouldn't use java.io.File, you use org.springframework.web.multipart.MultipartFile. You can either pass it in directly in the handler method, or make it a member of your Form Bean/Command Object. It gives you niceties like the original filename and content type.

As far as the "upload box" goes, you simply make an input element on your HTML page of type "file". The browser handles the rest.

I am not sure what you are asking in the 2nd part.

2
  • @CodeChimp-- i have set the MultiPartFile type as the content of request body-- i hope this is the correct/recommended way to use it? Thanks...
    – Arvind
    Mar 6, 2013 at 23:49
  • You can use the RequestBody, or just pass it as a RequestParameter on the method parameter. The answer to this question has an example: stackoverflow.com/questions/3577942/spring-mvc-file-upload-help
    – CodeChimp
    Mar 7, 2013 at 20: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.