簡體   English   中英

從android應用程序上傳圖像到服務器不起作用

[英]Upload image to server from android app not working

我正在嘗試編寫代碼以使用 php 將圖像從 android 應用程序上傳到服務器。 我試圖通過將其轉換為 Base64 並將其作為字符串發送

這是Java代碼:

 public class uploadImage extends AsyncTask< String, String, String>{

    Bitmap _image;

    uploadImage(Bitmap image){
        _image = image;
    }

    @Override
    protected String doInBackground(String... params) {
        HttpURLConnection con = null;
        BufferedOutputStream os= null;

        try {

            URL url = new URL("URL_TO_SERVER");
            con = (HttpURLConnection) url.openConnection();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            _image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
            byte[] byte_arr = byteArrayOutputStream.toByteArray();
            String _imageEncoded = Base64.encodeToString(byte_arr, Base64.DEFAULT);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("imageEncoded", _imageEncoded);
            String message = jsonObject.toString();

            con.setDoOutput(true);
            con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            con.setRequestProperty("X-Requested-With", "XMLHttpRequest");
            con.connect();

            os = new BufferedOutputStream(con.getOutputStream());
            os.write(message.getBytes());
            os.flush();

            return "";


        }  catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finally {
            if (con != null)
                con.disconnect();
            if (os != null)
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }
}//uploadImage

這是php代碼:

<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);  
$imageEncoded = $obj->{"imageEncoded"}

$image = base64_decode("$imageEncoded");

$alterName = rand();
$target= $_SERVER['DOCUMENT_ROOT']."/imagenes/";
$new_img_path =$target.$alterName.".jpg";               

file_put_contents( $new_img_path, $image );?>

由於某種原因它不起作用,有人可以告訴我我的錯誤是什么嗎? 或以更好的方法指導我。

使用以下類“Base64”:

    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    yourBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
    byte[] bArray = outStream.toByteArray();
    String imgEncoding = Base64.encodeBytes(bArray);

這是該課程的鏈接:

https://sourceforge.net/projects/iharder/files/base64/2.3/Base64-v2.3.7.zip/download

暫無
暫無

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

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