如何将图像上传到从库中选择的服务器?

时间:2014-12-18 09:45:41

标签: android image-uploading

我正在创建应用程序,我需要将上传图片从图库添加到服务器,我已经写过但没有得到任何答案,这里是How to upload image from gallary to server?问题是每当我从图库中选择并尝试发送时,它显示源文件不存在,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

开始意图从图库中选择图像文件...

startActivityForResult(new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI),54);

在活动结果上获取文件URI ...

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode != RESULT_CANCELED) {
        try {
            if (requestCode == 54 && resultCode != 0) {
                if (intent != null) {
                    Uri selectedImage = intent.getData();
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Could not load image",
                            Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

从URI获取文件字节...

private byte[] GetFileBytes(Uri uri)
{
    ByteArrayOutputStream bos = new ByteArrayOutputStream(200000);
    InputStream imageStream;
    try {
        imageStream = getContentResolver().openInputStream(uri);
        byte[] buffer;
        buffer = new byte[100000];
        while ((imageStream.read(buffer)) != -1) {
            bos.write(buffer);
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return bos.toByteArray();
}

从字节数组中获取MultipartEntity ...

private MultipartEntity getEntity(byte[] bytes)
{
    MultipartEntity entity = new MultipartEntity();
    InputStream in = new ByteArrayInputStream(bytes);
    ContentBody bin = new InputStreamBody(in, "Image_" + c.getTimeInMillis() + ".jpg");
    entity.addPart("image_query_string_variable_name", bin);
}

MultipartEntity是一类httpmime。你可以通过谷歌搜索轻松找到JAR。您需要从项目属性中将此jar文件添加到项目中。

发布到服务器......

private void PostData(MultipartEntity entity)
{
    HttpParams httpParameters = new BasicHttpParams();  
    HttpConnectionParams.setConnectionTimeout(httpParameters, 20000);
    HttpConnectionParams.setSoTimeout(httpParameters, 20000);
    DefaultHttpClient client = new DefaultHttpClient(httpParameters);

    HttpPost request = new HttpPost("http://www.you_server_url.com/someFileName.php");
    request.setEntity(entity);

    HttpResponse response = null;
    response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    //
    // Process the returned result from server...
    //
}

更多编辑:

byte[] fileBytes = null;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode != RESULT_CANCELED) {
        try {
            if (requestCode == 54 && resultCode != 0) {
                if (intent != null) {
                    Uri selectedImage = intent.getData();
                    fileBytes = GetFileBytes(selectedImage);
                } else {
                    fileBytes = null;
                    Toast.makeText(getApplicationContext(),
                            "Could not load image",
                            Toast.LENGTH_SHORT).show();
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

// when button is clicked...
public void onClick(View v)
{
    if(fileBytes != null)
    {
        MultipartEntity entity = getEntity(fileBytes);
        PostData(entity);
    }
}
祝你好运。 :)