java - 使用jsp和servlet上传文件

标签 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);


    }



}

最佳答案

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

没有。您还可以从请求中获取其他项目。

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 对象获取它。其他领域也类似。

关于java - 使用jsp和servlet上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26275484/

相关文章:

java - JAVA 中的 Composer 等价物?

Python 网络脚本不能在 apache 上运行

php - 是否可以在 mac 上的 xampp htdocs 中使用别名目录?

css - Java EE Web 应用程序中的路径相关问题

java - 在 Jersey 拦截器中缩小 html 和 js

java - struts2 date无法通过jquery datetimepicker获取时间

c# - UML 转 java 或 c# 工具?

java - Hibernate 找不到属性的 setter (org.hibernate.PropertyNotFoundException)

java - 是否可以将输出缓冲到 Log4j Mail Appender?

php - Pico Install 中的子页面导致 404