如何从Android设备上传位图图像?

时间:2010-11-03 08:15:17

标签: java android http multipartform-data

提前谢谢你。 我想从我的Android应用程序上传一些位图图像。 但是,我无法得到它。 你能为它推荐一些解决方案吗? 或收集我的源代码?

ByteArrayOutputStream bao = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://example.com/imagestore/post");
                MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
                byte [] ba = bao.toByteArray();
                try {
                    entity.addPart("img", new StringBody(new String(bao.toByteArray())));
                    httppost.setEntity(entity);
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // Execute HTTP Post Request
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
}

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

我发现这个解决方案确实很好,即使使用amazon ec2也能100%工作,请看一下这个链接:

Uploading files to HTTP server using POST on Android (link deleted).

与之前的答案相比,此解决方案不需要从Apache导入大型库httpmime

原始文章中的复制文字:

本教程介绍了使用Android SDK将数据(图像,MP3,文本文件等)上传到HTTP / PHP服务器的简单方法。

它包括在Android端上传工作所需的所有代码,以及PHP中用于处理文件上传和保存的简单服务器端代码。此外,它还为您提供有关如何在上传文件时处理基本自动化的信息。

在模拟器上测试时,记得通过DDMS或命令行将测试文件添加到Android的文件系统。

我们要做的是设置请求的相应内容类型,并将字节数组包含在帖子的主体中。字节数组将包含我们要发送到服务器的文件的内容。

您将在下面找到执行上传操作的有用代码段。该代码还包括服务器响应处理。

HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs.
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Set HTTP method to POST.
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    serverResponseCode = connection.getResponseCode();
    serverResponseMessage = connection.getResponseMessage();

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
}
catch (Exception ex)
{
    //Exception handling
}

如果您需要在上传文件时使用用户名和密码对用户进行身份验证,则下面的代码段会显示如何添加该文件。您所要做的就是在创建连接时设置授权标头。

String usernamePassword = yourUsername + “:” + yourPassword;
String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);
connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);

假设PHP脚本负责在服务器端接收数据。这样一个PHP脚本的示例可能如下所示:

<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} 
else
{
    echo "There was an error uploading the file, please try again!";
}
?>;

代码在Android 2.1和4.3上进行了测试。请记住在服务器端为脚本添加权限。否则,上传将无效。

chmod 777 uploadsfolder

uploads文件夹是上传文件的文件夹。如果您计划上传大于默认2MB文件大小限制的文件。您必须修改php.ini文件中的upload_max_filesize值。