2013-03-11 74 views
0

後,我成功上傳文本文件(比如Another.java)使用下面的代碼,但它給了我一個錯誤,而試圖打開上傳的文件。提前致謝。阿帕奇共享文件上傳,讓correpted文件上傳

fileUpload.jsp

<form action="test.jsp" method="post" enctype="multipart/form-data"> 
<input type="file" name="file"/> 
<br/> 
<input type="submit" value="Upload"> 
</form> 
</body> 

test.jsp的

<%@page import="org.apache.commons.fileupload.FileItem"%> 
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%> 
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%> 
<%@page import="java.io.*"%> 
<%@page import="java.util.*"%> 
<%-- <%@page import="org.apache.commons.io.*" %> --%> 
<%@page import="org.apache.commons.io.*"%> 

<%@page import="org.apache.commons.fileupload.FileUploadException"%> 

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<% 
    try { 
     String username = ""; 
     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(); 

       if (fieldname.equals("vsrd")) { 
        username = fieldvalue; 
       } 

       // ... (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(); 

       byte[] b = new byte[filecontent.available()]; 
       FileOutputStream fos = new FileOutputStream(
         "/home/visruth/Desktop/Out" + filename); 
       fos.write(b); 
       fos.close(); 
       // ... (do your job here) 
      } 
     } 
    } catch (FileUploadException e) { 
     throw new ServletException("Cannot parse multipart request.", e); 
    } 
%> 

錯誤,而試圖打開OutAnother.java

enter image description here

+1

您剛剛創建一個空的字節數組。您沒有閱讀過InputStream的內容。 – longhua 2013-03-11 07:22:23

+0

@ lhuang 哦!我錯過了。非常感謝你。 – Visruth 2013-03-11 07:41:46

回答

0

我固定它通過添加以下代碼:

byte[] b = new byte[filecontent.available()]; 
filecontent.read(b); 
1

在代碼中,你只是創建了一個空字節陣列。您沒有閱讀過InputStream的內容。 Inputstream#available()只是獲得可用長度。它不會從InputStream中讀取內容。

典型的方式是從InputStream中讀取和寫入的OutputStream:

FileInputStream is = new FileInputStream(
     new File("D:\\temp\\in.java")); 
FileOutputStream os = new FileOutputStream(
     new File("D:\\temp\\out.java")); 
byte[] buff = new byte[1000]; 
int length = -1; 
while ((length = is.read(buff)) != -1) { 
    os.write(buff, 0, length); 
} 
is.close(); 
os.close(); 

您還可以使用IOUtils#copy從公共-io的做這個工作。