简体   繁体   English

Java Servlet多文件上传变化

[英]Java Servlet Multiple File Upload Variation

Can someone help me with to come up with a Java Servlet that can upload files in this kind of variation or give me any idea how to it: 有人可以帮我提出一个Java Servlet,该Java Servlet可以上传这种变体形式的文件,或者告诉我如何做的事情:

5 file input type field, but fill in only 1 or 2 of them (in any file field), and upload those no. 5个文件输入类型字段,但仅填写其中的1个或2个(在任何文件字段中),然后上传编号。 of files. 文件。

I found out the problems to be: 我发现问题是:

1) If I fill in the file field not from the first one, then it will not upload my file. 1)如果我不是从第一个字段填写文件字段,那么它将不会上传我的文件。 eg I fill in the 3rd file field, and click upload. 例如,我填写第三个文件字段,然后单击上载。 The file won't be uploaded. 该文件将不会上传。 But if I fill in the first one, it will get uploaded. 但是,如果我填写第一个,它将被上传。 Same if I fill in any 2-3 fields, but if I don't fill them in order (1,2,3...), they won't be uploaded. 如果我填写2-3个字段,则相同,但如果我不按顺序填写(1,2,3 ...),则不会上传它们。

2) I have radio button below the file fields. 2)我在文件字段下面有单选按钮。 If I don't fill in all of the file fields, the radio button values won't be read by the servlet. 如果我没有填写所有文件字段,则servlet不会读取单选按钮的值。 Can someone enlighten me why this happen? 有人可以启发我为什么会这样吗?

In summary, it works if and only if I fill in all 5 file fields, and tick one of the radio button. 总而言之,当且仅当我填写所有5个文件字段并勾选单选按钮之一时,它才起作用。

The HTML code: HTML代码:

<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>Energy Efficient Color Mapping Texture Transformer</h3>
Select 5 images to upload: <br />
<form action="UploadServlet" method="post"
                    enctype="multipart/form-data">
<b>Image 1</b>                  
<input type="file" name="file1" size="50" />
<br />
<b>Image 2</b>
<input type="file" name="file2" size="50" />
<br />
<b>Image 3</b>
<input type="file" name="file3" size="50" />
<br />
<b>Image 4</b>
<input type="file" name="file4" size="50" />
<br />
<b>Image 5</b>
<input type="file" name="file5" size="50" />
<br /><br />
Select conversion scheme below: <br />
<input type="radio" name="scheme" value="1" /> Sat 25 Hue 9 <br />
<input type="radio" name="scheme" value="2" /> Sat 25 Hue 24 <br />
<input type="radio" name="scheme" value="3" /> Sat 25 Hue 36 <br />
<input type="radio" name="scheme" value="4" /> Sat 50 Hue 9 <br />
<input type="radio" name="scheme" value="5" /> Sat 70 Hue 9 <br />
<input type="radio" name="scheme" value="6" /> Sat 50 Hue 24 <br />
<input type="radio" name="scheme" value="7" /> Sat 70 Hue 36
<br /><br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>

So say, I want to just fill in Image 3 and 4, and upload those 2 images. 可以这么说,我只想填写图片3和4,然后上传那2张图片。 The servlet: Servlet:

// Import required java libraries
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {

private boolean isMultipart;
private String filePath;
private int maxFileSize = 5*1024*1024;
private int maxMemSize = 4 * 1024*1024;
private File file ;

public void init( ){

}
public void doPost(HttpServletRequest request, 
           HttpServletResponse response)
          throws ServletException, java.io.IOException {
  // Check that we have a file upload request
  isMultipart = ServletFileUpload.isMultipartContent(request);
  response.setContentType("text/html");
  java.io.PrintWriter out = response.getWriter( );
  if( !isMultipart ){
     out.println("<html>");
     out.println("<head>");
     out.println("<title>Servlet upload</title>");  
     out.println("</head>");
     out.println("<body>");
     out.println("<p>No file uploaded</p>"); 
     out.println("</body>");
     out.println("</html>");
     return;
  }
  DiskFileItemFactory factory = new DiskFileItemFactory();
  // maximum size that will be stored in memory
  factory.setSizeThreshold(maxMemSize);
  // Location to save data that is larger than maxMemSize.
  factory.setRepository(new File("c:\\temp"));

  // Create a new file upload handler
  ServletFileUpload upload = new ServletFileUpload(factory);
  // maximum file size to be uploaded.
  upload.setSizeMax( maxFileSize );

  try{ 
  // Parse the request to get file items.
  List fileItems = upload.parseRequest(request);

  // Process the uploaded file items
  Iterator i = fileItems.iterator();

  out.println("<html>");
  out.println("<head>");
  out.println("<title>Servlet upload</title>");  
  out.println("</head>");
  out.println("<body>");

  // Get the file location where it would be stored.
  filePath = 
         getServletContext().getInitParameter("file-upload");

  //Create calendar for folder naming purpose
  GregorianCalendar gcalendar = new GregorianCalendar();
  String date=String.valueOf(gcalendar.get(Calendar.DATE));
  String month=String.valueOf(gcalendar.get(Calendar.MONTH)+1);
  String year=String.valueOf(gcalendar.get(Calendar.YEAR));
  String hour=String.valueOf(gcalendar.get(Calendar.HOUR));
  String minute=String.valueOf(gcalendar.get(Calendar.MINUTE));
  String second=String.valueOf(gcalendar.get(Calendar.SECOND));

  //create a new filepath
  filePath= filePath + date+"-"+month+"-"+year+"_"+hour+minute+second;

  boolean newfolder= (new File(filePath)).mkdirs();

  if (newfolder){
    System.out.println("Created new folder");
  }

  while ( i.hasNext () ) 
  {
     FileItem fi = (FileItem)i.next();
     if ( fi.isFormField() )
     {
        out.println("is a form field <br>");
        String fieldName = fi.getFieldName();
        String fieldValue = fi.getString();
        out.println(fieldName+": "+fieldValue);
     }
     else
     //if ( !fi.isFormField () )    
     {
        // Get the uploaded file parameters
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        String contentType = fi.getContentType();
        boolean isInMemory = fi.isInMemory();
        long sizeInBytes = fi.getSize();
        // Write the file
        if( fileName.lastIndexOf("\\") >= 0 ){
           file = new File( filePath + "\\" +
           fileName.substring( fileName.lastIndexOf("\\"))) ;
        }else{
           file = new File( filePath + "\\" +
           fileName.substring(fileName.lastIndexOf("\\")+1)) ;
        }
        fi.write( file ) ;
        out.println("Uploaded Filename: " + fileName + "<br>");
     } 
  }
  out.println("</body>");
  out.println("</html>");
  }catch(Exception ex) {
   System.out.println(ex);
  }
  }
  public void doGet(HttpServletRequest request, 
                   HttpServletResponse response)
    throws ServletException, java.io.IOException {

    throw new ServletException("GET method used with " +
            getClass( ).getName( )+": POST method required.");
  } 
}

So far, I haven't seen any different variation than mine when I searched for multiple file upload using java servlet. 到目前为止,当我使用java servlet搜索多个文件上传时,没有看到与我不同的变化。

OK, so this problem occurs when any of the file field is empty. 单击确定,所以当任何文件字段为空时,会发生此问题。 Which means the fileName is also an empty string. 这意味着fileName也是一个空字符串。 One way to handle this problem is by adding a conditional to skip the empty files: 解决此问题的一种方法是通过添加条件来跳过空文件:

if( fileName.equals("")){
continue;
}

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

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