3

我正在尝试将图像从我的 android 设备发送到托管基于 C#.NET 的 Web 处理程序的 IIS 服务器。

我现在面临的根本问题是如何将其发送到服务器?
我已将图像转换为 base64 格式,但我必须在HTTP's POST对象中发送它的部分是我面临困境的地方。

                HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
                File data2send = new File(image_str);
                FileEntity fEntity = new FileEntity(data2send, "binary/octet-stream");
                httppost.setEntity(fEntity);


                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);

在上面的片段中^ 我发送 base64 字符串的行image_str不能File是显而易见的类型。

所以,我需要一些东西来转换这个 base64 字符串,以便将它发送到服务器,或者如果有人可以在这里彻底帮助我的话更好:D

我尝试了namevalue成对的方式..它没有用。

我发送的图像约为 3KB。

我的完整活动代码:

public class MainActivity extends Activity {

    InputStream inputStream;


    private class GetRouteInfo extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();



        }

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

       try 
       {
           Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);           
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); //compress to which format you want.
            byte [] byte_arr = stream.toByteArray();
            String image_str = Base64.encodeBytes(byte_arr);
            ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

            System.out.println("image_str: "+image_str);

            nameValuePairs.add(new BasicNameValuePair("image",image_str));

            try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
                //post.addHeader("zipFileName", zipFileName);
                //httppost.addHeader("image",image_str);

                File data2send = new File();

                //File data2send = new File(image_str);
                FileEntity fEntity = new FileEntity(data2send, "binary/octet-stream");
                httppost.setEntity(fEntity);


                //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                String the_string_response = convertResponseToString(response);
                //Toast.makeText(MainActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
                System.out.println("Response " + the_string_response);

            }catch(Exception e){
                  //Toast.makeText(MainActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
                System.out.println("ERROR " + e.getMessage());
                  System.out.println("Error in http connection "+e.toString());
            }

        }
       catch (Exception e) {
                Log.i("SvcMgr", "Service Execution Failed!", e);

            }

            finally {

                Log.i("SvcMgr", "Service Execution Completed...");

            }

            return null;
        }

        @Override
        protected void onCancelled() {
            Log.i("SvcMgr", "Service Execution Cancelled");
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            Log.i("SvcMgr", "Service Execution cycle completed");

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.img1);           
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream); //compress to which format you want.
        byte [] byte_arr = stream.toByteArray();
        String image_str = Base64.encodeBytes(byte_arr);
        ArrayList<NameValuePair> nameValuePairs = new  ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("image",image_str));

        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.248/imgup/Default.aspx");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            String the_string_response = convertResponseToString(response);
            Toast.makeText(MainActivity.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();
        }catch(Exception e){
              Toast.makeText(MainActivity.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();
              System.out.println("Error in http connection "+e.toString());
        }*/

        try {
            new GetRouteInfo().execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

     public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{

         String res = "";
         StringBuffer buffer = new StringBuffer();
         inputStream = response.getEntity().getContent();
         int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
         System.out.println("contentLength : " + contentLength);
         //Toast.makeText(MainActivity.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();
         if (contentLength < 0){
         }
         else{
                byte[] data = new byte[512];
                int len = 0;
                try
                {
                    while (-1 != (len = inputStream.read(data)) )
                    {
                        buffer.append(new String(data, 0, len)); //converting to string and appending  to stringbuffer…..
                    }
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                try
                {
                    inputStream.close(); // closing the stream…..
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                res = buffer.toString();     // converting stringbuffer to string…..

                System.out.println("Result : " + res);
                //Toast.makeText(MainActivity.this, "Result : " + res, Toast.LENGTH_LONG).show();
                //System.out.println("Response => " +  EntityUtils.toString(response.getEntity()));
         }
         return res;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

服务器端代码(在 C#.net 中):

protected void Page_Load(object sender, EventArgs e)
    {

        if (System.IO.Directory.Exists(Server.MapPath("~/Data")))
        {
        }
        else
        {
            System.IO.Directory.CreateDirectory(Server.MapPath("~/Data"));

        }

    if(Request.InputStream.Length !=0 && Request.InputStream.Length < 32768) {
        //Request.ContentType = "binary/octet-stream";
        Request.ContentType = "text/plain";

        Stream myStream = Request.InputStream;

        string fName = Request.Params["image"];

        byte[] imageBytes = Convert.FromBase64String(myStream.ToString());
        MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);

        // Convert byte[] to Image
        ms.Write(imageBytes, 0, imageBytes.Length);
        System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);

        string fileName = Server.MapPath("~/Data/").ToString() + "try1" + ".jpeg";
        image.Save(fileName);

        Request.InputStream.Close();


    }
    else
    {
    }

    }
4

2 回答 2

1

您实际上并未将名称/值对设置为 POST。您只是将 IMAGE 作为 base64 字符串发送。

尝试这样的事情:

httpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> parms;
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Your Url Here);

params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("image", BASE_64_STRING);

httppost.setEntity(new UrlEncodedFormEntity(params);
HttpResponse resp = httpclient.execute(httppost);
于 2013-05-23T17:08:48.117 回答
1

我最喜欢的一段代码。

Android 应用上传位置

我压缩图像(重新大小)只是为了保存(最后的代码)

Bitmap bitmap = resizeBitMapImage1(exsistingFileName, 800, 600);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,30, stream);
StrictMode.ThreadPolicy policy = new     StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image_data", Base64.encodeBytes(stream.toByteArray())));

// image_str = null;
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", FileName));

String url = "http://www.xyz.com/upload.aspx";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("DataUploaderOffline_Image ","Status--> Completed");

ASPX 页面代码

 Response.ContentType = "text/plain";
 string c = Request.Form["image_data"];
 string FileName = Request.Form["FileName"];
 byte[] bytes = Convert.FromBase64String(c);

 System.Drawing.Image image;
 using (MemoryStream ms = new MemoryStream(bytes))
 {
      image = System.Drawing.Image.FromStream(ms);
      image.RotateFlip(System.Drawing.RotateFlipType.Rotate90FlipNone);
      String Fname =   FileName + ".jpeg";
      image.Save(Server.MapPath("Image\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
      Response.End();
 }

*调整代码大小 *

public static Bitmap resizeBitMapImage1(String filePath, int targetWidth,
        int targetHeight) {
    Bitmap bitMapImage = null;
    try {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        double sampleSize = 0;
        Boolean scaleByHeight = Math.abs(options.outHeight - targetHeight) >= Math
                .abs(options.outWidth - targetWidth);
        if (options.outHeight * options.outWidth * 2 >= 1638) {
            sampleSize = scaleByHeight ? options.outHeight / targetHeight
                    : options.outWidth / targetWidth;
            sampleSize = (int) Math.pow(2d,
                    Math.floor(Math.log(sampleSize) / Math.log(2d)));
        }
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[128];
        while (true) {
            try {
                options.inSampleSize = (int) sampleSize;
                bitMapImage = BitmapFactory.decodeFile(filePath, options);
                break;
            } catch (Exception ex) {
                try {
                    sampleSize = sampleSize * 2;
                } catch (Exception ex1) {

                }
            }
        }
    } catch (Exception ex) {

    }
    return bitMapImage;
}
于 2013-05-23T17:09:41.977 回答