使用jsp和servlet上传文件

时间:2014-10-09 09:56:07

标签: java apache jsp servlets apache-commons

我正在使用Java开发Web应用程序。在我的索引页面中,我需要使用输入标签上传一个带有其他字段的文件,例如一些文本和数字。

这是我的jsp文件。

<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">

我发现了一些使用Apache commons的文章,但在所有这些文章中,我只能得到图片。所有其他值都设置为null。我所遵循的文章是this。 我需要知道如何获得其他值。 (在这种情况下类别,标题,照片等) 我怎样才能做到这一点? 谢谢!

修改 这是我的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);


    }



}

1 个答案:

答案 0 :(得分:1)

  

我发现了一些使用Apache公共文章的文章,但在所有这些文章中,我   只能得到图像

不。您也可以从请求中获取其他项目。

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
          }}

阅读文档here以了解有关此内容的更多信息以及此处的一个好主题values of input text fields in a html multipart form

更新:

String cat = item.getFieldName("category")代替request.getParameter("category");

因为您正在解析请求对象。所以你需要从FileItem对象获取它。同样适用于其他领域。