簡體   English   中英

將多個圖像上傳到服務器

[英]Uploading multiple images to server

用戶可以通過相機在Android端拍攝5-6張照片。 因此,我使用了ACTION_IMAGE_CAPTURE。 在onActivityResult中,我這樣做是為了收集相機拍攝的圖像的位圖。 假設第一個拍攝的照片和第二個拍攝的照片如下。

if(requestCode == 1)
{
    bitMap1 = (Bitmap)extras.get("data");
    imageView1.setImageBitmap(bitMap1);
    globalvar = 2;
}
if(requestCode == 2)
{
    bitMap1 = (Bitmap)extras.get("data");
    imageView2.setImageBitmap(bitMap2);
    globalvar = 2;
}

要將這些圖像發送到php服務器,請執行以下操作。

protected String doInBackground(Integer... args) {
            // Building Parameters


    ByteArrayOutputStream bao1 = new ByteArrayOutputStream();
    bitMap1.compress(Bitmap.CompressFormat.JPEG, 90, bao1);
    byte [] bytearray1 = bao1.toByteArray();
    String stringba1 = Base64.encode(bytearray1);


 ByteArrayOutputStream bao2 = new ByteArrayOutputStream();
    bitMap2.compress(Bitmap.CompressFormat.JPEG, 90, bao2);
    byte [] bytearray2 = bao2.toByteArray();
    String stringba2 = Base64.encode(bytearray2);


            String parameter1 = "tenant";
                String parameter2 = "price";

            List<NameValuePair> params = new ArrayList<NameValuePair>();

                params.add(new BasicNameValuePair("person",parameter1));
                params.add(new BasicNameValuePair("price",parameter2));
                params.add(new BasicNameValuePair("image1",stringba1));
                params.add(new BasicNameValuePair("image2",stringba2));

            JSONObject json = jParser.makeHttpRequest(requiredurl, "POST", params);


            Log.d("Details", json.toString());



                int success = json.getInt("connected");

                if (success == 1) {

                    //blah blah
                      }
        }

這是makeHttpRequest()方法

public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){

                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }       

       ................
       ....................... // Here the result is extracted and made it to json object
       .............................

        // return JSON 
        return jObj;  // returning the json object to the method that calls.

    }

以下是php代碼段:

$name = $_POST[person];
$price = $_POST[price];
$binary1 = base64_decode($image2);
$binary2 = base64_decode($image2);

$file1 = tempnam($uploadPath, 'image2');
$fp1  = fopen($file1, 'wb');
fwrite($fp1, $binary1);
fclose($fp1);
.................
............................

但是,我無法將圖像存儲在服務器的側面文件夾中。 甚至我在某些鏈接中都說過,在上傳多張圖片時,Base64不是更好的選擇。 有人可以建議我如何繼續嗎? 已經看到了鏈接以及許多其他鏈接,但是由於我必須隨同該圖像一起發送一些數據(例如人名,價格),因此無法按我的要求進行操作。 在此方面的任何幫助將不勝感激。

注意:即使有人可以建議我如何將上述臨時文件($ file1)保存在服務器文件夾中,我也將非常感激。

您是否考慮過使用FTP代替目前的方法? apache中有一個名為Apache的commons-net-ftp庫,可以輕松完成工作。

使用apache FTP庫

這是我很久以前就stackoverflow提出的一個問題。 我之前實現的代碼幾乎相同,但是我發現FTP方法更容易將文件上傳到服務器。

@TemporaryNickName如何與該圖像一起發送其他數據。 此外,我的圖像數據是位圖形式,而不是uri。 如何根據我現在的情況實現它?

*有很多教程向您展示如何將位圖轉換為圖像文件(這是臨時保存文件並在FTP完成后立即刪除的許多方法),此外,當您使用內置於相機的默認應用程序拍照時,您可以自動保存。 好了,發送數據應該單獨完成,在這種情況下,我將使用$ _POST編寫一個PHP腳本來接收數據,而不是將其保存到數據庫中或將其寫入XML *


要保存上傳的文件,請使用

move_uploaded_file($src, $path);

移動上傳的文件doc

要發送多種類型的數據,請使用MultipartEntity (通過問題中提供的鏈接)而不是URLEncodedEntity 這個想法是MultipartEntity僅包含不同類型的主體(例如StringBodyFileBody等)。 因此,如果您需要在Base64中發送圖像,請將它們作為StringBody添加到MultipartEntity (應使用setEntity將其設置為請求的實體)。

雖然,我強烈建議您將位圖保存在磁盤(SD卡)上,而改用FileBody 這將為您節省大量內存(使用Base64,您必須一次加載所有圖像),並且...如果用戶在上載時關閉應用程序怎么辦? 您將永遠丟失位圖。

PS不要忘記使用Service來上傳任務。

這是我的代碼段,希望對您有所幫助:

private class AsyncTask1 extends AsyncTask<Void, Void, String>{




    @Override
    protected String doInBackground(Void... params) {

        boolean response = false;

        try {

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            FileBody bin = new FileBody(new File("temp"));

            File tempImg  = new File("sdcard/signature.jpg");
            if(tempImg.exists())
            {
                checkimgfile=checkimgfile+"LPA"+tempImg;
                bin = new FileBody(tempImg, "image/jpg");
                reqEntity.addPart("txt_sign_lpa", bin);
                reqEntity.addPart("count_lpa",new StringBody("1"));
            }
            else
            {
                reqEntity.addPart("count_lpa",new StringBody("0"));
            }

                FileBody bin1 = new FileBody(new File("temp"));
                File tempImg1  = new File("sdcard/signature2.jpg");
                if(tempImg1.exists())
                {

                    checkimgfile=checkimgfile+"subject"+tempImg1;
                    bin1 = new FileBody(tempImg1, "image/jpg");
                    reqEntity.addPart("txt_sign", bin1);
                    reqEntity.addPart("count_subject",new StringBody("1"));
                }




                reqEntity.addPart("count",new StringBody("0"));


            reqEntity.addPart("name",new StringBody("Shaili"));
            reqEntity.addPart("age",new StringBody("47"));




            try
            {


            ConnectivityManager cm =
            (ConnectivityManager)getBaseContext().getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();


            if(activeNetwork!=null && activeNetwork.isAvailable() && activeNetwork.isConnected())
            {
                String xml = "";
                HttpParams httpParameters = new BasicHttpParams();  
                HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
                HttpConnectionParams.setSoTimeout(httpParameters, 100000);
                final HttpClient httpclient = new DefaultHttpClient(httpParameters);
                final HttpPost httppost = new HttpPost("https://www.xyz.com/abc.php");//url where you want to post your data.
                httppost.setParams(httpParameters);


                httppost.setEntity(reqEntity);
                httppost.addHeader("Accept", "text/html");

                httppost.addHeader("Host", "www.xyz.com");
                httppost.addHeader("User-Agent",
                        "Android ");

                HttpResponse response1 = null;
                String errMessage = "Error";
                try {

                    response1 = httpclient.execute(httppost);
                    final HttpEntity resEntity = response1.getEntity();
                    InputStream content = resEntity.getContent();
                    BufferedReader b = new BufferedReader(new InputStreamReader(
                            content));
                    xml = XmlParser.getTrimmedResponse(b);

                    if (response1 != null){
                        if(Integer.toString(response1.getStatusLine().getStatusCode()).equals("200")){
                            return "success";
                        }
                    }



                } catch (Exception e) {


                    e.printStackTrace();
                    errorstring=errorstring+e.getLocalizedMessage();
                    errMessage = "Network error";

                    return errMessage;
                }

            }
            else if(activeNetwork==null)
            {

                return "Available";
            }

            }
            catch(Exception e)
            {

            Toast.makeText(getBaseContext(), "Network Connection not available", 1).show();
            progressDialog.dismiss();

            }


        } catch (Exception e) {

            errorstring=errorstring+e.getLocalizedMessage();
            return "Network error";

        }
        return "abc";
    }       

    protected void onPostExecute(String result) {


    //do your stuff

    }
}

暫無
暫無

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

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