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

6

提前感谢您。 我想从我的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) {
}

1
你遇到了什么错误?你在服务器端使用的技术是什么?你确定问题不是出在客户端而是服务器端吗? - kgiannakakis
谢谢你的回复。所以我已经在GAE上开发了服务端,GAE报告了NotImageError()异常。我猜想是字符串编码错误或者必须使用InputStreamBody。 - freddiefujiwara
我达成了我的目标——使用文件名为“img.jpg”的InputStream。 :-) - freddiefujiwara
你介意分享一下你是如何编写InputStream实现的吗? - Carl
2个回答

3

你所参考的教程使用了现在已经被弃用的MultipartEntity。也许你应该编辑你的回答,这样人们就能知道。 - dephinera

1

我发现这个解决方案非常好,即使在Amazon EC2上也可以100%工作,看看这个链接:

使用Android进行POST上传文件到HTTP服务器(链接已删除)

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

从原始文章中复制的文本:

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

它包括所有在Android端使上传工作的所需代码,以及一个简单的PHP服务器端代码来处理文件上传和保存。此外,它还提供了有关如何在上传文件时处理基本授权的信息。

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

我们要做的是设置请求的适当内容类型,并将字节数组包含为post请求的主体。字节数组将包含我们想要发送到服务器的文件的内容。
下面您将找到一个有用的代码片段,执行上传操作。该代码还包括服务器响应处理。
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

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


看起来链接中提到的帖子已经不再可用了 :( - Seven
@SeverianoJaramilloQuintanar从已删除的链接中获取了文本。 - dikirill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接