15

I have a jsp with this code snippet in it.

<form name="AudioFileConversionForm" enctype="multipart/form-data" method="post" >
Choose File: <input type="file" id="audioFile" name="audioFile"><br>
<input type="submit" value="upload">
</form>

This is my controller in spring.

public String convertFile(HttpServletRequest request, HttpSession session) {

    String audioFile = request.getParameter("audioFile");
    System.out.println(request.getParameter("audioFile"));
    System.out.println("Audio File Conversion Successful");
}

I am unable to retrieve the name of the file, it shows null. I know that I can retrieve the name using JQuery or javascript, but I don't want to use them both. I want to do it using pure java. Can anyone please help me?

2
  • have you tried any of code, if yes, then let us know, whether you got the solution or not, if not then explain your requirement further. Commented Dec 19, 2012 at 7:19
  • I am trying the answers one by one. I will surely update the best suited answer from below. Thank you all for the answers. Commented Dec 19, 2012 at 7:30

5 Answers 5

21

When you upload the file, request is instance of org.springframework.web.multipart.MultipartHttpServletRequest. So you can cast it in your method convertFile(). See below :

public String convertFile(HttpServletRequest request, HttpSession session) {
    // cast request
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    // You can get your file from request
    CommonsMultipartFile multipartFile =  null; // multipart file class depends on which class you use assuming you are using org.springframework.web.multipart.commons.CommonsMultipartFile

    Iterator<String> iterator = multipartRequest.getFileNames();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        // create multipartFile array if you upload multiple files
        multipartFile = (CommonsMultipartFile) multipartRequest.getFile(key);
    }

    // logic for conversion
}

However I am unable to retrieve (receiving null value) the name of the file that I chose in the JSP page.

---> To get file name you can get it as :

multipartFile.getOriginalFilename();  // get filename on client's machine
multipartFile.getContentType();       // get content type, you can recognize which kind of file is, pdf or image or doc etc
multipartFile.getSize()          // get file size in bytes

To make file upload work, you need to make sure you are creating multipart resolver bean as below :

<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="100000"/>
</bean>

Reference : Spring documentation

Sign up to request clarification or add additional context in comments.

1 Comment

I am accepting this answer but may I suggest you to add the code for creating an instance for CommonsMultiPartFile? This will help the on-goers' work easy. Or perhaps a way or a link to guide them regarding the same?
3

use MultipartFile utility and try this

MultipartRequest multipartRequest = (MultipartRequest) request;
                Map map = multipartRequest.getFileMap();
                MultipartFile mfile = null;
                for (Iterator iter = map.values().iterator(); iter.hasNext();) {
                    mfile = (MultipartFile) iter.next();
                                String fileName = mfile.getOriginalFilename()
    }

Or you can try apache commons file upload.

Check this link : http://commons.apache.org/fileupload/using.html

Comments

2

File name cannot be directly retrieved. You can use Apache Commons Fileupload API -

// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (item.isFormField()) {
       // Process a normal field
       String name = item.getFieldName();
       String value = item.getString();

    } else {
        // Process a file upload field 
    String fileName = item.getName();
    // DO further processing

    }
}

More details -

http://commons.apache.org/fileupload/using.html

It can also be done with just Java but obviously more code will be required.

Comments

1

But, first of all, you will need Commons Fileupload API, which will help you to use file.getFieldName() to display the Form Field Name and file.getContentType() to display Type of File and file.getName() to display File Name

public String convertFile(HttpServletRequest request, HttpSession session) {
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if(!isMultipart) {
            out.println("File Not Uploaded");
    }
    else{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
          } catch (FileUploadException e) {
            e.printStackTrace();
        }
        try {
            FileItem file = (FileItem) items.get(0);
            out.print("Field Name :"+file.getFieldName()); // Display the field name
            out.print("Content Type :"+file.getContentType()); // Display Type of File
            out.print("File Name :"+file.getName()); // Display File Name
        } catch (Exception e) {
            out.print(e);
        }
    }
 }

2 Comments

upload.parseRequest(request) is returning an empty list. Thus an IndexOutOfBoundsException on FileItem file = (FileItem) items.get(0).
@Freakyuser upload.parseRequest(request); create array of file. If it is showing arrayindexoutofbound error, which means, it is getting file request.
0
Iterator iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();

    if (item.isFormField()) {
       // Process a normal field
       String name = item.getFieldName();
       String value = item.getString();

    } else {
        // Process a file upload field 
    String fileName = item.getName();
    // DO further processing

    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.