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 6879427
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T04:50:42+00:00 2026-05-27T04:50:42+00:00

I have a input type=file tag in my html which allows user to select

  • 0

I have a input type=file tag in my html which allows user to select multiple files. The action for the form is a REST web service:

@POST
@Path("savefile")
@Produces ({MediaType.TEXT_PLAIN})
public String createObjects(
        @FormDataParam("datafile") FormDataMultiPart file,
        @FormParam("username") String unm
        //@Context HttpServletRequest request
        ){....}

Initially I used the request object to retrieve all FileItems in the request and then saved it to the server. No problem with that. Now I want to send a string data along with the files. For that I read that the parameters need to be of type FormDataParam. Hence I have added that parameter. This is my client code :

<form id="form1" action="http://comp1:8080/RestWSGS/jersey/UploadFiles/savefile"
        enctype="multipart/form-data" method="post">
        <input name="username" type="text" style="display:none" value="abc"/>
  <input id="loadId" multiple="multiple" 
        type="file" name="datafile" required="required" autofocus="autofocus"
        onchange="selectFiles(this)"/>
  <div>
    <input style="display: none;" type="submit" value="Send">
  </div>
 </form>  

I am not sure what must be the type of the file parameter to allow multiple files in it????
Either the file parameter gives me multiple files OR do I have to revert back to the @Context injection?? If so how will I retrieve the string parameter?

Any help is welcome!

EDIT:
I have modified my REST ws to the following:

@POST
@Path("savefile")
//@Consumes (MediaType.MULTIPART_FORM_DATA)
public void createObjects(
        //@FormDataParam("datafile") FormDataMultiPart file,
        //@FormParam("username") String unm
        @Context HttpServletRequest request
        )
{
    try
    {
        FileHandler f;
        f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\")  + "/mylog.log");
        logger.addHandler(f);

    }
    catch (SecurityException e1)
    {
        logger.info(e1.getMessage());

    }
    catch (IOException e1)
    {
        logger.info(e1.getMessage());
        //e1.printStackTrace();
    }


    ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
            0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ;
    ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring
    (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2);
    String user = request.getParameter("username");
    logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH);


    try
    {
        for (Part part : request.getParts())
        {
                try
                {
                    logger.info("part = " + part.getName());
                    if (!part.getName().equalsIgnoreCase("username"))
                    {
                        String fileName = processFileName(part.getName());
                        part.write(new File(ApplicationConstants.ROOTPATH + user + "\\" + fileName).getPath());
                    }

                    else
                    {
                         user = request.getParameter("username");
                         logger.info("user = " + user);
                    }
                }
                catch (IOException e)
                {
                    logger.info(e.getMessage());

                }
        }
    }
    catch (IOException e)
    {

    }
    catch (ServletException e)
    {

    }
}

But I am always getting the value from request.getParameter(“username”) as null. I dont know what is going wrong!! Is it illegal to send other data as well in a multipart/form-data form?? I need some pointers here. Please suggest any improvements in this code.

  • 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-27T04:50:42+00:00Added an answer on May 27, 2026 at 4:50 am

    The following is the solution that works for me. The request parts in case of a multipart/formdata request can be accessed using the input stream in the part. I wanted to send a string and some files to my REST web service.I found a ServletFileUpload/ FIleItem example posted at a couple of web sites but I could not retrieve the string( I think it gives an exception if all data is not of file type). Hence I modified my web service to the following and not I can do the processing of a string and some files:

        private static  Logger   logger = Logger.getLogger("UploadFiles");
    @POST
    @Path("savefile")
    public void createObjects(@Context HttpServletRequest request)
    {
        try
        {
            FileHandler f;
            f = new FileHandler(new File (getClass().getResource("/" +getClass().getName().substring(
                    0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\")  + "/mylog.log");
            logger.addHandler(f);
    
        }
        catch (SecurityException e1)
        {
            logger.info(e1.getMessage());
    
        }
        catch (IOException e1)
        {
            logger.info(e1.getMessage());
        }
        ApplicationConstants.ROOTPATH = new File (getClass().getResource("/" +getClass().getName().substring(
                0, getClass().getName().indexOf("."))).getPath()).getParent().replaceAll("\\\\", "\\\\\\\\") ;
        ApplicationConstants.ROOTPATH = ApplicationConstants.ROOTPATH.substring
        (0, ApplicationConstants.ROOTPATH.indexOf("\\") + 2);
        String user = request.getParameter("username");
        logger.info("ApplicationConstants.ROOTPATH" + ApplicationConstants.ROOTPATH);
        logger.info("username" + user);
        try
                    {
            for (Part part : request.getParts())
            {
    
                        logger.info("part = " + part.getName());
                        if (!part.getName().equalsIgnoreCase("username"))
                        {
                            try {
                            BufferedInputStream in = new BufferedInputStream(part.getInputStream());
                            String filename = getFilename(part);
                            boolean success = (new File(ApplicationConstants.ROOTPATH + user + "\\")).mkdir();
                            if (success) {
                            System.out.println("Directory: " + ApplicationConstants.ROOTPATH + user .trim()+ "\\" + " created");
                            }  
                            else
                            {
                                System.out.println("not created");
                            }
                            FileOutputStream out = new FileOutputStream(ApplicationConstants.ROOTPATH + user  + "\\" + filename);
    
                            byte[] data = new byte[1000];
                            int bytesRead = 0;
                            int offset = 0;
                            while (offset < part.getSize())
                            {
                              bytesRead = in.read(data);
                              if (bytesRead == -1)
                              {
                                  break;
                              }
                              offset += bytesRead;
                               out.write(data);
                            }
    
                            in.close();
    
                            if (offset != part.getSize())
                            {
                              throw new IOException("Only read " + offset + " bytes; Expected " + part.getSize() + " bytes");
                            }
                            out.flush();
                            out.close();
                            }
                            catch (Exception e) 
                            {
                                logger.info(e.getMessage());
                            }
                        }
                        else
                        {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
                            StringBuilder value = new StringBuilder();
                            char[] buffer = new char[1024];
                            reader.read(buffer);
                            value.append(buffer);
                             user = value.toString().trim();
                             logger.info("user = " + value);
                        }
    
    }
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (ServletException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    

    Hope this helps someone!!

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

Sidebar

Related Questions

I have an input form with two textareas allowing a user to type in
my last question on pointer cursors. in Html you have a input file tag.
How do I restrict file types with the HTML input file type? I have
Hi I have a simple form that allows a user to input a name,
I have a simple input field inside a form tag: <body> <form action=#> <label>Input</label>
I have a class which enables forms with a file-type input to be submitted
I have an ASP.NET Webform and inside the form I have an input type
I have an input of type text , from which I have already entered
I have an input field on my page where the user will type in
I have this input text: <html><head><meta http-equiv=content-type content=text/html; charset=utf-8></head><body><table cellspacing=0 cellpadding=0 border=0 align=center width=603>

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.