简体   繁体   English

如何使用上传功能将数据从JSP传输到servlet?

[英]How to transfer data from JSP to servlet with upload function?

I have a JSP page with an HTML form: 我有一个带有HTML表单的JSP页面:

在此处输入图片说明

Here is my code: 这是我的代码:

<form method="post" action="UploadServlet" name="upload" enctype="multipart/form-data" >

            Select file to upload: <input type="file" name="uploadFile" >
            <input type="text" name="fileNames" > 
        <input type="hidden" name="form_id" value="652973" > 
            <br/><br/> 
            <input type="submit" value="Upload" />

        </form>

web.xml web.xml中

<display-name>UploadServletApp</display-name>
  <servlet>
    <description></description>
    <display-name>UploadServlet</display-name>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>net.code.upload.UploadServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>
</web-app>

UploadServlet.java UploadServlet.java

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

        PrintWriter writer = response.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    String paths="C:\\Uploaded_FIle\\";
    factory.setRepository(new File(paths));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    //String uploadPath = getServletContext().getRealPath("")+ File.separator + UPLOAD_DIRECTORY;
    String uploadPath =paths+File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }
try {

            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();

            // iterates over form's fields
            while ( iter.hasNext () ) 
             {
                FileItem fi = (FileItem)iter.next();
                if ( !fi.isFormField () )  {
                    String fieldName = fi.getFieldName();
                    String fileName = fi.getName();
                    boolean isInMemory = fi.isInMemory();
                    long sizeInBytes = fi.getSize();
                    File file = new File( uploadDir + "yourFileName") ;
                    fi.write( file ) ;
                     }
             }

            request.setAttribute("message", "Upload has been done successfully!\n"  + uploadDir  + "<br>");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }

The problem is, I am able to upload the file, but the values which I'm sending are not coming, like fileNames,form_id. 问题是,我能够上载文件,但是我要发送的值没有出现,例如fileNames,form_id。 I am not getting any values which entered through jsp page as well as hard-coded values. 我没有通过jsp页面输入的任何值以及硬编码的值。

This snippet if ( !fi.isFormField () ) in your code skips the fields which you are sending and only processes the files that are sent. if ( !fi.isFormField () )您的代码中的if ( !fi.isFormField () )代码段跳过了您要发送的字段,并且仅处理已发送的文件。 So to get the fields you need to handle both the cases: 因此,要获取字段,您需要处理两种情况:

  1. When the field is a form field like radio-button, text, etc. 如果该字段是表单字段,例如单选按钮,文本等。
  2. When the field is a file. 当字段是文件时。

This should give you an idea. 这应该给您一个想法。

 try {
    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();
            // ... (do your job here)
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            InputStream fileContent = item.getInputStream();
            // ... (do your job here)
        }
    }
} catch (FileUploadException e) {
    throw new ServletException("Cannot parse multipart request.", e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM