2011-08-02 141 views
11

我正在開發一個J2ME客戶端,它必須使用HTTP將文件上傳到Servlet。Java Http客戶端通過POST上傳文件

該servlet部分使用Apache通用FileUpload

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
{  

    ServletFileUpload upload = new ServletFileUpload(); 
    upload.setSizeMax(1000000); 

    File fileItems = upload.parseRequest(request); 

    // Process the uploaded items 
    Iterator iter = fileItems.iterator(); 
    while (iter.hasNext()) { 
     FileItem item = (FileItem) iter.next(); 
     File file = new File("\files\\"+item.getName()); 
     item.write(file); 
    } 
} 

共享上傳似乎可以只上傳多文件覆蓋,但沒有應用程序/八位字節流。

但是,對於客戶端沒有Multipart類,在這種情況下,可以使用任何HttpClient庫。

其他選項可能是使用HTTP塊上傳,但我還沒有找到一個明確的例子來說明如何實現,特別是在servlet方面。

我的選擇是: - 實現對HTTP上傳塊 一個servlet - 實現一個原始客戶端的HTTP多創造

我不知道如何實現以上都不是選項。 有什麼建議嗎?

回答

0

沒有進入血淋淋的細節你的代碼看起來很好。

現在你需要服務器端。我建議你使用雅加達FileUpload,所以你不必執行任何操作。只需部署和配置。

+5

你看了這個問題嗎? **發佈的代碼是**已經使用FileUpload的服務器端。 – BalusC

29

通過HTTP發送文件應該使用multipart/form-data編碼進行。你的servlet部分沒問題,因爲它已經使用Apache Commons FileUpload來解析multipart/form-data請求。

然而,您的客戶端部分顯然不好,因爲您似乎將原始文件內容寫入請求主體。您需要確保您的客戶發送正確的multipart/form-data請求。究竟該怎麼做取決於你用來發送HTTP請求的API。如果是普通香草java.net.URLConnection,那麼你可以在this answer的底部附近找到一個具體的例子。如果您使用Apache HttpComponents Client對於這一點,那麼這裏有一個具體的例子:

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(url); 

MultipartEntity entity = new MultipartEntity(); 
entity.addPart("file", new FileBody(file)); 
post.setEntity(entity); 

HttpResponse response = client.execute(post); 
// ... 

無關到具體的問題,在你的服務器端代碼中的錯誤:

File file = new File("\files\\"+item.getName()); 
item.write(file); 

這將潛在覆蓋以前上傳的具有相同名稱的文件。相反,我建議使用File#createTempFile()

String name = FilenameUtils.getBaseName(item.getName()); 
String ext = FilenameUtils.getExtension(item.getName()); 
File file = File.createTempFile(name + "_", "." + ext, new File("/files")); 
item.write(file); 
+0

我怎樣才能得到這個文件服務器端例如通過使用requset。getParameter我們獲得字符串值,那麼文件體中的文件如何... – Aniket

+0

@Aniket:就像您使用常規HTML表單一樣。 – BalusC

+4

[MultipartEntity](http://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntity.html)現已棄用。 –

0

感謝所有代碼IVE狙擊......這是一些回來。

Gradle 

compile "org.apache.httpcomponents:httpclient:4.4" 
compile "org.apache.httpcomponents:httpmime:4.4" 



import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringWriter; 
import java.util.Map; 

import org.apache.commons.io.IOUtils; 
import org.apache.http.HttpEntity; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.CloseableHttpResponse; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.entity.ContentType; 
import org.apache.http.entity.mime.MultipartEntityBuilder; 
import org.apache.http.entity.mime.content.FileBody; 
import org.apache.http.entity.mime.content.StringBody; 
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients; 


public class HttpClientUtils { 

    public static String post(String postUrl, Map<String, String> params, 
      Map<String, String> files) throws ClientProtocolException, 
      IOException { 
     CloseableHttpResponse response = null; 
     InputStream is = null; 
     String results = null; 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 

     try { 

      HttpPost httppost = new HttpPost(postUrl); 

      MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 

      if (params != null) { 
       for (String key : params.keySet()) { 
        StringBody value = new StringBody(params.get(key), 
          ContentType.TEXT_PLAIN); 
        builder.addPart(key, value); 
       } 
      } 

      if (files != null && files.size() > 0) { 
       for (String key : files.keySet()) { 
        String value = files.get(key); 
        FileBody body = new FileBody(new File(value)); 
        builder.addPart(key, body); 
       } 
      } 

      HttpEntity reqEntity = builder.build(); 
      httppost.setEntity(reqEntity); 

      response = httpclient.execute(httppost); 
      // assertEquals(200, response.getStatusLine().getStatusCode()); 

      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       is = entity.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(is, writer, "UTF-8"); 
       results = writer.toString(); 
      } 

     } finally { 
      try { 
       if (is != null) { 
        is.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      try { 
       if (response != null) { 
        response.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      httpclient.close(); 
     } 

     return results; 
    } 

    public static String get(String getStr) throws IOException, 
      ClientProtocolException { 
     CloseableHttpResponse response = null; 
     InputStream is = null; 
     String results = null; 
     CloseableHttpClient httpclient = HttpClients.createDefault(); 

     try { 
      HttpGet httpGet = new HttpGet(getStr); 
      response = httpclient.execute(httpGet); 

      assertEquals(200, response.getStatusLine().getStatusCode()); 

      HttpEntity entity = response.getEntity(); 
      if (entity != null) { 
       is = entity.getContent(); 
       StringWriter writer = new StringWriter(); 
       IOUtils.copy(is, writer, "UTF-8"); 
       results = writer.toString(); 
      } 

     } finally { 

      try { 
       if (is != null) { 
        is.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      try { 
       if (response != null) { 
        response.close(); 
       } 
      } catch (Throwable t) { 
       // No-op 
      } 

      httpclient.close(); 
     } 

     return results; 
    } 

} 
0

下面的代碼可以用來上傳文件與HTTP客戶端4.x版(以上回答使用MultipartEntity現在已廢棄)

String uploadFile(String url, File file) throws IOException 
{ 
    HttpPost post = new HttpPost(url); 
    post.setHeader("Accept", "application/json"); 
    _addAuthHeader(post); 
    MultipartEntityBuilder builder = MultipartEntityBuilder.create(); 
    // fileParamName should be replaced with parameter name your REST API expect. 
    builder.addPart("fileParamName", new FileBody(file)); 
    //builder.addPart("optionalParam", new StringBody("true", ContentType.create("text/plain", Consts.ASCII))); 
    post.setEntity(builder.build()); 
    HttpResponse response = getClient().execute(post);; 
    int httpStatus = response.getStatusLine().getStatusCode(); 
    String responseMsg = EntityUtils.toString(response.getEntity(), "UTF-8"); 

    // If the returned HTTP response code is not in 200 series then 
    // throw the error 
    if (httpStatus < 200 || httpStatus > 300) { 
     throw new IOException("HTTP " + httpStatus + " - Error during upload of file: " + responseMsg); 
    } 

    return responseMsg; 
}