Android 通过HTTP POST 上传图片文件

Sending images can be done using the  HttpComponents libraries . Download the latest HttpClient (currently 4.0.1 ) binary with dependencies package and copy  apache-mime4j-0.6.jar  and  httpmime-4.0.1.jar  to your project and add them to your Java build path.

You will need to add the following imports to your class.

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:

public void post(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for(int index=0; index < nameValuePairs.size(); index++) {
            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
                // If the key equals to "image", we use FileBody to transfer the data
                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, localContext);
    } catch (IOException e) {
        e.printStackTrace();
    }
}


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Android 中上文件时,我们可以使用流式上的方式,即通过分块上的方式将大文件分为多个小块进行上。具体实现步骤如下: 1. 添加 OkHttp 库依赖:在 app 的 build.gradle 文件中添加以下代码: ```gradle dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.0' } ``` 2. 创建一个 RequestBody 对象,该对象包含文件内容。 ```java File file = new File(filePath); RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file); ``` 3. 创建一个 Request 对象,设置上文件的 URL 和其他参数。注意,这里不需要设置 Content-Length 头部,因为我们将文件分块上。 ```java Request request = new Request.Builder() .url(uploadUrl) .post(requestBody) .build(); ``` 4. 创建一个 OkHttpClient 对象,并使用它发送请求。在发送请求之前,我们需要通过设置 Interceptor 来实现分块上。具体来说,我们需要在请求头部中添加 Content-Type 和 Content-Range 头部,以及在请求体中添加文件的小块内容。 ```java OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Response originalResponse = chain.proceed(originalRequest); if (originalResponse.code() != 308) { return originalResponse; } // 获取已上的字节数 long uploadedBytes = originalResponse.body().contentLength(); while (true) { // 读取下一块文件内容 byte[] buffer = new byte[1024 * 1024]; int bytesRead = inputStream.read(buffer); if (bytesRead == -1) { break; } // 计算本次上的字节数和总字节数 long totalBytes = file.length(); long numBytes = bytesRead; long nextUploadedBytes = uploadedBytes + numBytes; // 构造本次上的请求 Request request = originalRequest.newBuilder() .header("Content-Type", "application/octet-stream") .header("Content-Range", "bytes " + uploadedBytes + "-" + (nextUploadedBytes - 1) + "/" + totalBytes) .method("POST", new RequestBody() { @Override public MediaType contentType() { return MediaType.parse("application/octet-stream"); } @Override public long contentLength() { return numBytes; } @Override public void writeTo(BufferedSink sink) throws IOException { sink.write(buffer, 0, bytesRead); } }) .build(); // 发送本次上的请求 Response response = chain.proceed(request); if (response.code() != 308) { return response; } // 更新已上的字节数 uploadedBytes = nextUploadedBytes; } // 所有块上完成后,返回最终的响应 return originalResponse.newBuilder() .body(ResponseBody.create(null, new byte[0])) .build(); } }) .build(); Response response = client.newCall(request).execute(); ``` 在上面的代码中,我们首先发送一个空请求,得到服务器返回的 308 状态码和已上的字节数。然后,我们通过循环读取文件内容,并构造包含文件小块内容的请求来分块上文件。每个请求包含 Content-Type 和 Content-Range 头部,Content-Range 头部指示本次上的字节范围。最后,我们将所有块上完成后,发送一个空请求来告诉服务器上已完成。 注意,上面的代码中使用了一个 inputStream 对象来读取文件内容,这个对象需要在外部进行初始化。具体来说,我们可以在一个线程中读取文件内容,并将 inputStream 对象递给分块上的代码块。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值