简体   繁体   English

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

[英]How to upload Bitmap Image from a android device?

Thank you in advance. 先感谢您。 I'd like to upload some bitmap image from my android app. 我想从我的Android应用程序上传一些位图图像。 but , I can't get it. 但是,我无法得到它。 Could you recommend some solutions for it. 你能为它推荐一些解决方案吗? or collect my source code? 或收集我的源代码?

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) {
}

I found this solution really well created and 100% working even with amazon ec2, take a look into this link: 我发现这个解决方案确实很好,即使使用amazon ec2也能100%工作,请看一下这个链接:

Uploading files to HTTP server using POST on Android (link deleted). 使用Android上的POST将文件上传到HTTP服务器(链接已删除)。

Compare to previous answer, this solution doesn't require to import huge library httpmime from Apache. 与之前的答案相比,此解决方案不需要从Apache导入大型库httpmime

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. 它包括在Android端进行上传工作所需的所有代码,以及PHP中用于处理文件上传和保存的简单服务器端代码。 Moreover, it also gives you information on how to handle the basic autorization when uploading the file. 此外,它还为您提供有关如何在上载文件时处理基本自动化的信息。

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. 假设PHP脚本负责在服务器端接收数据。 Sample of such a PHP script could look like this: 这样一个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. 代码在Android 2.1和4.3上进行了测试。 Remember to add permissions to your script on server side. 请记住在服务器端为脚本添加权限。 Otherwise, the uploading won't work. 否则,上传将无效。

chmod 777 uploadsfolder

Where uploadsfolder is the folder where the files are uploaded. uploadsfolder是上传文件的文件夹。 If you plan to upload files bigger than default 2MB file size limit. 如果您计划上传大于默认2MB文件大小限制的文件。 You will have to modify the upload_max_filesize value in the php.ini file. 您必须修改php.ini文件中的upload_max_filesize值。

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

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