将文件从Java客户端上传到HTTP服务器

我想上传几个文件到HTTP服务器。 基本上我需要的是一些POST请求到服务器几个参数和文件。 我见过只上传文件的例子,但没有find如何传递额外的参数。

这样做的最简单和免费的解决scheme是什么? 有没有人有我可以学习的任何file upload的例子? 我一直在Google上search几个小时,但是(也许这只是其中的一个)找不到我所需要的。 最好的解决办法是不涉及任何第三方类或图书馆的东西。

您通常会使用java.net.URLConnection来触发HTTP请求。 您通常还会使用multipart/form-data编码来处理混合POST内容(二进制和字符数据)。 点击链接,它包含信息和一个示例如何组成一个multipart/form-data请求体。 该规范在RFC2388中有更详细的描述。

这是一个开球的例子:

 String url = "http://example.com/upload"; String charset = "UTF-8"; String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); ) { // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } // Request is lazily fired whenever you need to obtain information about response. int responseCode = ((HttpURLConnection) connection).getResponseCode(); System.out.println(responseCode); // Should be 200 

使用Apache Commons HttpComponents客户端等第三方库时,此代码不会太冗长。

Apache Commons FileUpload的一些不正确的build议在这里只是在服务器端的兴趣。 你不能在客户端使用它,也不需要它。

也可以看看

  • 使用java.net.URLConnection来触发和处理HTTP请求

这里是你如何使用Apache HttpClient (这个解决scheme是为那些谁不介意使用第三方库):

  MultipartEntity entity = new MultipartEntity(); entity.addPart("file", new FileBody(file)); HttpPost request = new HttpPost(url); request.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); 

点击链接获取示例file uploadclint java与Apache HttpComponents

http://hc.apache.org/httpcomponents-client-ga/httpmime/examples/org/apache/http/examples/entity/mime/ClientMultipartFormPost.java

和库下载链接

https://hc.apache.org/downloads.cgi

使用4.5.3.zip它在我的代码中工作正常

和我的工作代码

 import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; 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; import org.apache.http.util.EntityUtils; public class ClientMultipartFormPost { public static void main(String[] args) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet"); FileBody bin = new FileBody(new File("E:\\meter.jpg")); StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN); HttpEntity reqEntity = MultipartEntityBuilder.create() .addPart("bin", bin) .addPart("comment", comment) .build(); httppost.setEntity(reqEntity); System.out.println("executing request " + httppost.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httppost); try { System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); } EntityUtils.consume(resEntity); } finally { response.close(); } } finally { httpclient.close(); } } } 
 public static String simSearchByImgURL(int catid ,String imgurl) throws IOException{ CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String result =null; try { HttpPost httppost = new HttpPost("http://api0.visualsearchapi.com:8084/vsearchtech/api/v1.0/apisim_search"); StringBody catidBody = new StringBody(catid+"" , ContentType.TEXT_PLAIN); StringBody keyBody = new StringBody(APPKEY , ContentType.TEXT_PLAIN); StringBody langBody = new StringBody(LANG , ContentType.TEXT_PLAIN); StringBody fmtBody = new StringBody(FMT , ContentType.TEXT_PLAIN); StringBody imgurlBody = new StringBody(imgurl , ContentType.TEXT_PLAIN); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("apikey", keyBody).addPart("catid", catidBody) .addPart("lang", langBody) .addPart("fmt", fmtBody) .addPart("imgurl", imgurlBody); HttpEntity reqEntity = builder.build(); httppost.setEntity(reqEntity); response = httpClient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { // result = ConvertStreamToString(resEntity.getContent(), "UTF-8"); String charset = "UTF-8"; String content=EntityUtils.toString(response.getEntity(), charset); System.out.println(content); } EntityUtils.consume(resEntity); }catch(Exception e){ e.printStackTrace(); }finally { response.close(); httpClient.close(); } return result; } 
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { return; } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(MAX_MEMORY_SIZE); factory.setRepository(new File(System.getProperty("java.io.tmpdir"))); String uploadFolder = getServletContext().getRealPath("") + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer 

并使用<form enctype="multipart/form-data">并在html中使用<input type="file">

这是一个这样做的方法: http : //commons.apache.org/fileupload/ 。 如果你愿意的话,你可以偷看源代码。

这可能取决于你的框架。 (他们每个人都可以有一个更简单的解决scheme)。

但要回答你的问题:这个function有很多外部库 。 看看这里如何使用apache commons fileupload。