2013-07-20 16 views
1

我想在android中實現一個聊天應用程序。在我的應用程序中,我想上傳服務器上的文件,所以我使用此代碼在服務器端監聽文件請求。使用Java代碼創建文件上傳請求

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

    response.setContentType("text/html;charset=UTF-8"); 
    // Create path components to save the file 
    final String path = "/home/vibhor/vibhor"; 
    final Part filePart = request.getPart("file"); 
    final String fileName = getFileName(filePart); 
    OutputStream out = null; 
    InputStream filecontent = null; 
    final PrintWriter writer = response.getWriter(); 
    try { 
     out = new FileOutputStream(new File(path + File.separator 
       + fileName)); 
     filecontent = filePart.getInputStream(); 

     int read = 0; 
     final byte[] bytes = new byte[1024]; 

     while ((read = filecontent.read(bytes)) != -1) { 
      out.write(bytes, 0, read); 
     } 
     writer.println("New file " + fileName + " created at " + path); 
    } catch (FileNotFoundException fne) { 
     writer.println("You either did not specify a file to upload or are " 
       + "trying to upload a file to a protected or nonexistent " 
       + "location."); 
     writer.println("<br/> ERROR: " + fne.getMessage()); 

    } finally { 
     if (out != null) { 
      out.close(); 
     } 
     if (filecontent != null) { 
      filecontent.close(); 
     } 
     if (writer != null) { 
      writer.close(); 
     } 
    } 
} 

如果我使用HTML表單如再上面的代碼做一個文件請求工作

<form action="UploadServlet" method="post" 
        enctype="multipart/form-data"> 
<input type="file" name="file" size="50" /> 
<br /> 
<input type="submit" value="Upload File" /> 
</form> 

所以我想用下面的代碼在客戶方提出同樣的要求(在Android應用程序)

public static void uploadFile(String selectedPath, String fileType, 
     String fileName) { 
    HttpURLConnection httpUrlConnection = null; 
    DataOutputStream dataOutputStream = null; 
    DataInputStream dataInputStream = null; 
    String boundary = "*****"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    String urlString = "http://localhost:8080/FileUploadServlet1/UploadServlet"; 
    File file = new File(selectedPath); 
    try { 
     FileInputStream fileInputStream = new FileInputStream(file); 
     URL url = new URL(urlString); 
     httpUrlConnection = (HttpURLConnection) url.openConnection(); 
     httpUrlConnection.setDoInput(true); 
     httpUrlConnection.setConnectTimeout(50000000); 
     httpUrlConnection.setDoOutput(true); 
     httpUrlConnection.setUseCaches(false); 
     httpUrlConnection.setChunkedStreamingMode(maxBufferSize); 
     httpUrlConnection.setRequestMethod("POST"); 
     httpUrlConnection.setRequestProperty("Connection", "Keep-Alive"); 
     httpUrlConnection.setRequestProperty("Content-Type", 
       "multipart/form-data;boundary=" + boundary); 
     httpUrlConnection.setRequestProperty("filename", fileName); 
     httpUrlConnection.setRequestProperty("filetype", fileType); 

     dataOutputStream = new DataOutputStream(
       httpUrlConnection.getOutputStream()); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 
     int offset = 0; 
     bytesRead = fileInputStream.read(buffer, offset, bufferSize); 
     while (bytesRead > 0) { 
      dataOutputStream.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     } 
     fileInputStream.close(); 
     dataOutputStream.flush(); 
     dataOutputStream.close(); 
    } catch (MalformedURLException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    try { 
     dataInputStream = new DataInputStream(
       httpUrlConnection.getInputStream()); 
     dataInputStream.close(); 
    } catch (IOException ioex) { 
     ioex.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

但在這種情況下,我getti ng此例外

final String fileName = getFileName(filePart);

我也用Apache的文件上傳庫但在這種情況下,也得到了我此行

列表fileItems = upload.parseRequest(要求)沒有價值;

那麼我應該怎麼做uploadFile()方法 請幫忙。

+1

那麼是什麼問題?你的代碼看上去像是 – NINCOMPOOP

+0

。除了代碼之外,還需要告訴問題是什麼? –

回答

2

下面是在服務器上上傳文件的示例代碼。您需要外部庫使其工作,如apache常見,http默劇http核心。使用外部庫的代碼很容易理解和清理。

public static String post(String url,String[] args) throws UnsupportedEncodingException { 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpContext localContext = new BasicHttpContext(); 
     HttpPost httpPost = new HttpPost(url); 

     FileBody bin = new FileBody(new File(args[0]));//"/sdcard/DCIM/cam.jpg"));// 
     long size = bin.getContentLength(); 

     MultipartEntity reqEntity = new MultipartEntity(); 
     reqEntity.addPart("image1", bin); 
     String content = "-"; 
     try { 
      httpPost.setEntity(reqEntity); 
       HttpResponse response = httpClient.execute(httpPost, localContext); 
       HttpEntity ent = response.getEntity(); 
       InputStream st = ent.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(st, writer); 
       content = writer.toString();     

     } catch (IOException e) {     
      return "false"; 
     } 
     return content; 
    } 
+1

感謝Husyn你的回答已經解決了我的問題。 –

+0

不客氣:) – Husyn

+1

以下是如何發送附加參數: 'reqEntity.addPart(「mode」,new StringBody(「create」)); reqEntity.addPart(「list_name」,new StringBody(「nn-dlist」));' –