小编典典

使用Http Post发送图像

django

我想使用Http Post将图像从android客户端发送到Django服务器。该图像是从图库中选择的。目前,我正在使用列表值名称对来将必要的数据发送到服务器,并从JSON中接收来自Django的响应。是否可以对图像使用相同的方法(对于JSON响应中嵌入的图像使用URL)?

另外,哪种方法更好:远程访问图像而不从服务器下载图像或将其下载并存储在位图数组中并在本地使用?图像数量很少(<10个),尺寸很小(50 * 50浸入)。

解决这些问题的任何教程将不胜感激。

编辑:从图库中选择的图像在将其缩放到所需大小后会发送到服务器。


阅读 622

收藏
2020-03-25

共1个答案

小编典典

我将假设你知道要上传的图像的路径和文件名。将此字符串作为键名添加到你的NameValuePair使用image中。

可以使用HttpComponents库发送图像。下载具有依赖项包的最新HttpClient(当前为4.0.1)二进制文件,并将其复制apache-mime4j-0.6.jar并复制httpmime-4.0.1.jar到你的项目中,然后将其添加到Java构建路径中。

你将需要在类中添加以下导入。

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;

现在,你可以创建一个MultipartEntity将图像附加到POST请求。以下代码显示了如何执行此操作的示例:

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();
    }
}

我希望这可以帮助你在正确的方向上有所帮助。

2020-03-25