繁体   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