Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7022529
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T23:35:40+00:00 2026-05-27T23:35:40+00:00

I’ve written a Servlet that handles file uploads using the Apache commons file upload

  • 0

I’ve written a Servlet that handles file uploads using the Apache commons file upload library. Here is some of the code:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

            // Set size threshold for storing upload
            fileItemFactory.setSizeThreshold(1 * 1024 * 50); // 50 KB

            // Set temporary directory to store uploaded files above threshold size
            fileItemFactory.setRepository(new File(TEMP_DIRECTORY));

            ServletFileUpload upload = new ServletFileUpload(fileItemFactory);

            //HashMap<String, String> params = new HashMap<String, String>();


            FileItemIterator iterator = upload.getItemIterator(request);
            upload.setSizeMax(REQUEST_MAX_SIZE);

            List items = upload.parseRequest(request);
            Iterator it = items.iterator();

            while (it.hasNext()) {
                FileItem item = (FileItem) it.next();

                if(item.isFormField()) {

                } else {
                    String contentType = item.getContentType();
                    String fileName = item.getName();
                    String fieldName = item.getFieldName();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    File uploadedFile = new File(PATH + "new_audio1.amr");

                    item.write(uploadedFile);

                    System.out.println("Field: " + fieldName);
                    System.out.println("File name: " + fileName);
                    System.out.println("Size: " + sizeInBytes);
                    System.out.println("Is in memory:" + isInMemory);
                }
            }

        } catch (Exception ex) {
            throw new ServletException(ex);
        }
    } else {
        throw new ServletException();
    }

For some reason that escapes me the List ‘items’ is empty so I can’t grab the uploaded file.

For the upload itself, I’ve written some java code:

File audioFile = new File("C:\\Users\\Soto\\Desktop\\test recording.amr");

    String url = "http://localhost:8080/AudioFileUpload/UploadServlet";
    String charset = "UTF-8";

    // random values
    String latitude = "145";
    String longitude = "132";
    String speed = "0";


    String query;
    try {
        query = String.format("latitude=%s&longitude=%s&speed=%s", URLEncoder.encode(latitude, charset), URLEncoder.encode(longitude, charset), URLEncoder.encode(speed, charset));
    } catch (UnsupportedEncodingException e) {
        query = String.format("latitude=%s&longitude=%s&speed=%s", latitude, longitude, speed);
    }

    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httpPost = new HttpPost(url + "?" + query);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(audioFile, "audio/AMR");
    mpEntity.addPart("audioFile", cbFile);

    httpPost.setEntity(mpEntity);

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        System.out.println(response.getStatusLine());

        if(responseEntity != null) 
            System.out.println(EntityUtils.toString(responseEntity));

        if(responseEntity != null) {
            EntityUtils.consume(responseEntity);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It feels to me like the file is being attached and uploaded correctly.
I also tried doing it through HTML with a multipart/form-data post request, but the file still wasn’t found.

What am I doing wrong?

EDIT:
I removed the line at the beginning of the doPost() along with the if statement:

ServletFileUpload.isMultipartContent(request);

And then the upload worked correctly. Is it possible that this method consumes the request’s ‘input/output/whatever it is’ stream?

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T23:35:40+00:00Added an answer on May 27, 2026 at 11:35 pm

    EDIT: I removed the line at the beginning of the doPost() along with the if statement:

    ServletFileUpload.isMultipartContent(request);
    

    And then the upload worked correctly. Is it possible that this method consumes the request’s ‘input/output/whatever it is’ stream?

    This is strange. All that method does is checking if the request method equals to POST and if the Content-Type header starts with multipart/. Here’s an extract of the source of the currently latest Commons FileUpload API version (which hasn’t changed much across years):

    public static final boolean isMultipartContent(
            HttpServletRequest request) {
        if (!"post".equals(request.getMethod().toLowerCase())) {
            return false;
        }
        String contentType = request.getContentType();
        if (contentType == null) {
            return false;
        }
        if (contentType.toLowerCase().startsWith(MULTIPART)) {
            return true;
        }
        return false;
    }
    

    You see, nothing shocking.

    Perhaps you’re using a very obscure/buggy servlet container which manifests a bug that the request body will implicitly be consumed when you call request.getMethod() or getContentType().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am using Paperclip to handle profile photo uploads in my app. They upload
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
link Im having trouble converting the html entites into html characters, (&# 8217;) i
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.