簡體   English   中英

如何從Android設備上傳位圖圖像?

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

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

我發現這個解決方案確實很好,即使使用amazon ec2也能100%工作,請看一下這個鏈接:

使用Android上的POST將文件上傳到HTTP服務器(鏈接已刪除)。

與之前的答案相比,此解決方案不需要從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
}

如果您需要在上傳文件時使用用戶名和密碼對用戶進行身份驗證,則下面的代碼段會顯示如何添加該文件。 您所要做的就是在創建連接時設置Authorization標頭。

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值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM