我想将图片从Android应用上传到远程服务器。我使用Asp.Net作为服务器端来存储图像。以下是android端和c#的代码,但我无法做到。
Android Code,其中encodedString是Base64编码字符串。我想把它发送到服务器。
private class JSONParseProfilePic extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profile.this);
pDialog.setMessage("Uploading image");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONStudentParser jParser1 = new JSONStudentParser();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("encodedData", encodedString));
String url="http://127.0.0.1/webservice/imageUpload.aspx";
JSONObject json = jParser1.getJSONFromUrl(url, params);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
String result = json.getString("result").toString();
Toast.makeText(Profile.this, result, Toast.LENGTH_LONG).show();
pDialog.dismiss();
} catch (JSONException e) {
// e.printStackTrace();
String ms=e.getMessage();
Toast.makeText(Profile.this, "Error"+ms, Toast.LENGTH_LONG).show();
}
}
}
}
Asp.Net代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Drawing;
public partial class webservice_imageUpload : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string vTitle = "";
if (!string.IsNullOrEmpty(Request.Form["encodedData"]))
{
vTitle = Request.Form["encodedData"];
}
Base64ToImage(vTitle);
//image.Save(Server.MapPath("~/webservice/img.png"), System.Drawing.Imaging.ImageFormat.Png);
}
public System.Drawing.Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
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);
return image;
}
}
谢谢。