0

我想在我的程序中获取下拉值,以便将字符串合并到我的文件路径中,以便路径将根据用户输入动态更改。在我使用 o'reilly api 之前,我是 apache commoms 的新手。

这是我的代码:

 @Override
public void doPost(HttpServletRequest request, 
           HttpServletResponse response)
          throws ServletException, java.io.IOException 
{
       //FileItem f1;
   String d1= request.getParameter("sel1");
    String d2=request.getParameter("sel2");
    String d3="/home/adapco/Desktop/output";
    String conc=d3+"/"+d1+"/"+d2+"/";
    filePath=(new StringBuilder()).append(conc).toString();
 //      filePath="/home/adapco/Desktop/output/";
  isMultipart = ServletFileUpload.isMultipartContent(request);
}

我尝试调试并且我得到了 wright 文件路径,但是在继续进行时,fileItems 显示 size=0 并且由于 size0 而它没有进入循环。

    filePath="/home/adapco/Desktop/output/";

如果我将上传路径传递给 filePath 它工作正常。

  List fileItems = upload.parseRequest(request);    
  Iterator i = fileItems.iterator();
  while ( i.hasNext () ) 
  {
     FileItem fi = (FileItem)i.next();
     if ( !fi.isFormField () )  
     {         
        String fieldName = fi.getFieldName();
        String fileName = fi.getName();
        String contentType = fi.getContentType();
        boolean isInMemory = fi.isInMemory();
        long sizeInBytes = fi.getSize();
        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>"+filePath);

     }

我的 html :

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
 <title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
 Select a file to upload: <br />
 <form action="upload" method="post"
                    enctype="multipart/form-data">
<input type="file" name="file">
 <br />
<select name="sel1"> 
<option label ="1">aerospace</option>
<option label ="2">automotive</option>
</select>
<select name="sel2">
<option label="1">internal</option>
<option label="2">demo</option>
 </select>
 <input type="submit" value="Upload File" />
 </form>
 </body>
</html>
4

1 回答 1

1

request.getParameter()应删除呼叫。它们导致请求正文在 Apache Commons FileUpload 解析之前被解析。request.getParameter()不应在请求multipart/form-data中使用。

您需要elseif (!fi.isFormField()).

if (!fi.isFormField()) {
    // Collect uploaded files.
}
else {
    // Collect normal form fields.
}

另请参阅FileUpload 用户指南此答案

于 2012-05-18T11:44:17.787 回答