【问题标题】:Android - Upload image along with request dataAndroid - 上传图片和请求数据
【发布时间】:2013-11-29 21:43:18
【问题描述】:

我想通过 android 应用将图像上传到我的服务器,但是我还想将其他数据与图像一起传递(身份验证、意图等)。

我通常会提出这样的要求:

http://server/script.php?t=authtoken&j_id=12&... etc

但是,我假设我不能简单地添加另一个包含图像字节数组的查询参数,因为这会导致 URL 的大小约为数百万个字符。

&image=001101010010110111010001010101010110100101000101010100010... etc

我不知道应该如何处理这个问题,如果有任何建议,我将不胜感激。如果我无法通过 http 请求发送数据,我将如何处理传入的数据服务器端?

谢谢。

【问题讨论】:

    标签: java php android upload


    【解决方案1】:

    这就是我如何让它为那些将来可能会发现它的人工作的。

    对于这个例子,假设我们要使用参数t=ABC123id=12www.server.com 的根目录上查询PHP 脚本upload.php。除了这个请求,我们还想上传存储在java.io.File 对象img 中的图像。我们还将期待服务器的响应,让我们知道上传是否成功。

    安卓端

    在 android 端,您将需要以下 JAR:

    apache-mime4j-core-0.7.2.jar
    

    可用here 和:

    httpclient-4.3.1.jar
    httpcore-4.3.jar
    httpmime-4.3.1.jar
    

    可用here

    这是一个关于如何发出多部分请求并获得响应的 sn-p:

    public String uploadRequest(String address, File img)
    {
        HttpParams p = new BasicHttpParams();
        p.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        DefaultHttpClient client = new DefaultHttpClient(p);
    
        HttpPost post = new HttpPost(address);
    
        // No need to add regular params as parts. You can if you want or
        // you can just tack them onto the URL as usual.
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("image", new FileBody(img));
    
        post.setEntity(builder.build());
    
        return client.execute(post, new ImageUploadResponseHandler()).toString();
    }
    
    private class ImageUploadResponseHandler implements ResponseHandler<Object>
    {
        @Override
        public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException
        {
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity);
        }
    }
    

    在代码中使用此方法的示例(假设变量img 已声明包含您要上传的图像的File 对象):

    // Notice regular params can be included in the address
    String address = "http://www.server.com/upload.php?t=ABC123&id=12";
    
    String resp = uploadRequest(address, img);
    
    // Handle response
    

    PHP 端

    对于服务端脚本,文本参数可以通过PHP的$_REQUEST对象正常访问:

    $token = $_REQUEST['token'];
    $id = $_REQUEST['id'];
    

    上传的图片可以通过存储在 PHP $_FILES 对象中的信息来访问(更多信息请参见 PHP 文档):

    $img = $_FILES['img'];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 2017-05-30
      • 2019-03-21
      相关资源
      最近更新 更多