我正在尝试将图像从我的 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
{
}
}