简体   繁体   English

Android Studio:将图像上传到Web API

[英]Android studio: upload image to web API

I need to make app that take photo, place photo in image view and when I click button to upload to web API service. 我需要制作用于拍照的应用程序,将照片放置在图像视图中,然后单击按钮上传到Web API服务。

My problem is when I try upload photo, I have next error in code. 我的问题是当我尝试上传照片时,代码中出现下一个错误。

public void makeHTTPCall() {

    prgDialog.setMessage("Invoking php");
    StringEntity se = null;

    try{
        se = new StringEntity(params.toString());
        se.setContentType("application/json");
    }
    catch (UnsupportedEncodingException e){
        e.printStackTrace();
        return;
    }

    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

    AsyncHttpClient image = new AsyncHttpClient();

    image.post(uploadURL, se, new AsyncHttpResponseHandler()

在此处输入图片说明

This is my error. 这是我的错误。 And my imports 而我的进口

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

As u can i see, I have imported .RequestParams and .StringEntity 如你所见,我已经导入了.RequestParams和.StringEntity

And when I run app I have this: 当我运行应用程序时,我有以下内容:

在此处输入图片说明

Any idea what to do ? 你知道该怎么办吗?

You are using AsyncHttpClient, and the lib is support file upload with easy way. 您正在使用AsyncHttpClient,并且lib是支持文件上传的简便方法。

image.post(uploadURL, se, new AsyncHttpResponseHandler()

'se' is not StringEntity as like log result 'StringEntity cannot be converted to RequestParams. “ se”不是StringEntity,就像日志结果“ StringEntity无法转换为RequestParams”一样。

image.post(targetUrl, params, Responsehandler(){});

You should do like this. 你应该这样

This is a sample code for file upload with AsyncHttpClient: 这是使用AsyncHttpClient上传文件的示例代码:

RequestParam params = new RequestParams();
params.put("key1", "value1");
params.put("key2", "value2");

File imgFile = new File(filePath);
try {
      params.put("file",imgFile);
} catch(FileNotFoundException e) {}

AsyncHttpClient image = new AsyncHttpClient();
image.post(uploadURL, params, new AsyncHttpResponseHandler(){});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM