我正在尝试将图像从Android手机发送到.NET服务器,安卓代码: -
package com.example.imageupload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
InputStream mInputStream;
String mUrl = "http://10.0.2.2:49246/WebSite1/";
// Async task helps to run network operations in Non-UI thread..
private class GetRouteInfo extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
try
{
//resize the bitmap...
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/android.jpg";
Bitmap bitmap = resizeBitMapImage1(path, 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.encodeToString(stream.toByteArray(),Base64.NO_WRAP)));
stream.flush();
stream.close();
bitmap.recycle();
nameValuePairs.add(new BasicNameValuePair("FileName", "TrueSeeImage"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(mUrl);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response1 = httpclient.execute(httppost);
Log.i("response", response1.toString());
Log.i("DataUploaderOffline_Image ","Status--> Completed");
}
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);
new GetRouteInfo().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
mInputStream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
System.out.println("contentLength : " + contentLength);
if (contentLength < 0){
}
else{
byte[] data = new byte[512];
int len = 0;
try
{
while (-1 != (len = mInputStream.read(data)) )
{
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
mInputStream.close(); // closing the stream…..
}
catch (IOException e)
{
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
System.out.println("Result : " + res);
}
return res;
}
// Method to compress image..
// Input : filepath, target width, target height..
// Output : resized bitmap image..
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;
}
}
.NET部分是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
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)
{
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("save\\" + Fname), System.Drawing.Imaging.ImageFormat.Jpeg);
Response.End();
}
}
}
}
当我尝试从android浏览器访问服务器端代码时,它在调试模式下命中服务器端代码,但是当我从eclipse运行程序或从eclipse调试程序时,它没有命中代码视觉工作室。可能是什么原因?