java 如何从安卓设备上传位图图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4085155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:42:37  来源:igfitidea点击:

How to upload Bitmap Image from a android device?

javaandroidhttpmultipartform-data

提问by freddiefujiwara

Thank you in advance. I'd like to upload some bitmap image from my android app. but , I can't get it. Could you recommend some solutions for it. or collect my source code?

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

回答by dikirill

I found this solution really well created and 100% working even with amazon ec2, take a look into this link:

我发现这个解决方案创建得非常好,即使在亚马逊 ec2 上也能 100% 工作,请查看此链接:

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

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

Compare to previous answer, this solution doesn't requireto import huge library httpmimefrom Apache.

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

Copied text from original article:

从原始文章复制文本:

This tutorial shows a simple way of uploading data (images, MP3s, text files etc.) to HTTP/PHP server using Android SDK.

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

It includes all the code needed to make the uploading work on the Android side, as well as a simple server side code in PHP to handle the uploading of the file and saving it. Moreover, it also gives you information on how to handle the basic autorization when uploading the file.

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

When testing it on emulator remember to add your test file to Android's file system via DDMS or command line.

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

What we are going to do is set the appropriate content type of the request and include the byte array as the body of the post. The byte array will contain the contents of a file we want to send to the server.

我们要做的是设置请求的适当内容类型,并包含字节数组作为帖子的正文。字节数组将包含我们要发送到服务器的文件的内容。

Below you will find a useful code snippet that performs the uploading operation. The code includes also server response handling.

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

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
}

If you need to authenticate your user with a username and password while uploading the file, the code snippet below shows how to add it. All you have to do is set the Authorization headers when the connection is created.

如果您在上传文件时需要使用用户名和密码验证您的用户,下面的代码片段显示了如何添加它。您所要做的就是在创建连接时设置 Authorization 标头。

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

Let's say that a PHP script is responsible for receiving data on the server side. Sample of such a PHP script could look like this:

假设一个 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!";
}
?>;

Code was tested on Android 2.1 and 4.3. Remember to add permissions to your script on server side. Otherwise, the uploading won't work.

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

chmod 777 uploadsfolder

Where uploadsfolder is the folder where the files are uploaded. If you plan to upload files bigger than default 2MB file size limit. You will have to modify the upload_max_filesize value in the php.ini file.

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