vigamage
vigamage

Reputation: 2125

uploading files using jsp and servlet

I am developing a web application using Java. From my index page I need to upload a file with some other fields such as some texts and numbers using input tags.

this is my jsp file.

<select name="category">
    <option value="">-Select-</option>
    <option value="Mobile Phones">Mobile Phones</option>
    <option value="Automobile">Automobile</option>
    <option value="Computers">Computers</option>
</select><br/><br/>

<label>Title: </label><input type="text" name="Title"/><br/><br/>
<label>Photo: </label><input type="file" name="photo"/><br/><br/>
<label>Description: </label><input type="text" name="description"/><br/><br/>
<label>Price: </label><input type="text" name="price"/><br/><br/>
<input type="submit" value="Post">

I found some articles which use Apache commons, but in all of that, I can get only the image. All the other values get set to null. The article I followed is this. I need to know how to get other values as well. (In this case category, title, photo etc.) How can I do that? Thank you!

EDIT: This is my servlet.

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;



import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.im.dao.PostAdDao;
import com.im.dao.PostAdDaoImpl;
import com.im.entities.Advertiesment;



@WebServlet("/postAd")
@MultipartConfig
public class PostAdServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private final String UPLOAD_DIRECTORY = "C:/uploadss";

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

        Advertiesment ad = new Advertiesment();
        PostAdDao pad = new PostAdDaoImpl();
        PrintWriter out = response.getWriter();

        String name = null;


        if(ServletFileUpload.isMultipartContent(request)){
            try {
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

                for(FileItem item : multiparts){
                    if(item.isFormField()){


                        String cat = request.getParameter("category");
                        System.out.println("INFO: Category : "+cat);

                        if( cat != null ){
                            ad.setCategory(cat);

                        }
                        String title = request.getParameter("adTitle");
                        if( title != null ){
                            ad.setTitle(title);
                            System.out.println("INFO: Title : "+title);
                        }

                        String des = request.getParameter("description");
                        if(des != null){
                            ad.setDescription(des);
                            System.out.println("INFO: Description : "+des);
                        }
                        try{
                        Double price = Double.parseDouble(request.getParameter("price"));
                        if(price != null){
                            ad.setPrice(price);
                            System.out.println("INFO: Price : "+price);
                        }
                        }catch(Exception e){
                            System.out.println("ERROR: Occured while setting price in servlet");
                        }



                    }else{

                        name = new File(item.getName()).getName();
                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));

                    }
                }

                //File uploaded successfully
                request.setAttribute("message", "Advertiesment Posted Successfully");
                System.out.println("INFO: Advertiesment Posted Successfully");
                System.out.println("INFO: File name : "+name);
                ad.setPhoto(name);
            } catch (Exception ex) {
                request.setAttribute("message", "File Upload Failed due to " + ex);
                System.out.println("\nERROR: Occured while posting the advertiesment! "+ex );
            }          

        }else{
            //request.setAttribute("message","Sorry this Servlet only handles file upload request");
        }

        //request.getRequestDispatcher("/result.jsp").forward(request, response);


        String msg = pad.postAd(ad);


    }



}

Upvotes: 1

Views: 536

Answers (1)

Santhosh
Santhosh

Reputation: 8207

I found some articles which use Apache commons, but in all of that, I can get only the image

No . you can get other items also from the request .

DiskFileUpload upload = new DiskFileUpload();
List<FileItem> items = upload.parseRequest(request);
   for (FileItem item : items) {
        if (item.isFormField()) {
                 //get form fields here 
         }
         else {
                  //process file upload here
          }}

Read the documentation here to understand more on this and also a nice thread here values of input text fields in a html multipart form

Update:

String cat = item.getFieldName("category") instead of request.getParameter("category");

Because you are parsing the request object . so you need to get it from FileItem object . similarly for other fields too.

Upvotes: 1

Related Questions