-1

I am trying to upload a file using JSP but I'm getting and error and no file is uploaded.

Servlet code that I'm using for upload.

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

/**
 *
 * @author Hemal
 */
@MultipartConfig
public class UploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    private static final String DATA_DIRECTORY = "data";
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2;
    private static final int MAX_REQUEST_SIZE = 1024 * 1024;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        File file;
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        ServletContext context = request.getServletContext();
        String filePath = context.getInitParameter("file-upload");
        PrintWriter out=response.getWriter();
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.contains("multipart/form-data"))) {

            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File("data"));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);//ERROR ON THIS LINE

                // Process the uploaded file items
                Iterator i = fileItems.iterator();


                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();
                        String fileName = fi.getName();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath
                                    + fileName.substring(fileName.lastIndexOf("\\")));
                        } else {
                            file = new File(filePath
                                    + fileName.substring(fileName.lastIndexOf("\\") + 1));
                        }
                        fi.write(file);
                        out.println("Uploaded Filename: " + filePath
                                + fileName + "<br>");
                    }
                }

                } catch (Exception ex) {
                System.out.println(ex);
            }
        }
    }
}

Error I am receiving on line

`List fileItems = upload.parseRequest(request);`

is HttpServletRequest cannot be converted to RequestContext

I tried many options but didn't succeed.

Thanks.

EDIT

Other links with file upload in jsp only shows part of code without saving actual file to a user defined directory. I would like to have a code for saving a file also to a directory. So I think this is not a duplicate question.

Hemal
  • 3,682
  • 1
  • 23
  • 54
  • You must show the error message. – Elvermg Jul 02 '16 at 04:02
  • Possible duplicate of [File upload error in servlet while using Apache Tomcat 7.0.40.0](http://stackoverflow.com/questions/16768086/file-upload-error-in-servlet-while-using-apache-tomcat-7-0-40-0) or http://stackoverflow.com/questions/17590108/jsp-upload-file-failed – Taha Jul 02 '16 at 04:03
  • @Elvermg I already did show the error message in question itself. – Hemal Jul 02 '16 at 04:09
  • @Taha, the link you gave, I already tried and visited it, but it doesnt show how to save an uploaded file. – Hemal Jul 02 '16 at 04:10
  • Check this post, it has the same solution form @Taha comment. http://stackoverflow.com/questions/16768086/file-upload-error-in-servlet-while-using-apache-tomcat-7-0-40-0 – Elvermg Jul 02 '16 at 04:12
  • @Elvermg I already checked that post, but I need a code to save the file also. In the above answer, 'DO YOUR JOB HERE' part is there and I want that also. – Hemal Jul 02 '16 at 04:14
  • 1
    Can you please show your whole stack trace? – PVR Jul 02 '16 at 05:42
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. – Roman C Jul 03 '16 at 09:15

1 Answers1

0

You can use this:

InputStream content = uploadedFile.getInputStream();
byte[] fileArray = new byte[chooseTheSize];  //Here you must use a size big enough.
content.read(fileArray);

//fileArray is your file.

Elvermg
  • 427
  • 6
  • 12