目前正在使用Volley
上傳一個Image
到服務器,但圖片上傳0kb
,沒有名稱甚至,我從Android上傳圖片的方式,我首先把我的位圖到一個String
然後,在服務器端的C#
代碼轉字符串回Bitmap
,下面是我的Java代碼:圖片上傳android Java + Asp.net(C#)
private String UPLOAD_URL ="http://xxxxx:8092/PoliceApp/ImageUpload.aspx";
private void onUploading() {
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
//Disimissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(CrimesReporting.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(CrimesReporting.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
selectedFilePath = getStringImage(bitmap);
// Uri selectedImageUri = data.getData();
//String video = getVideo(selectedImageUri);
File fileAttachment;
//Getting Image Name
String contact = contact_crimes.getText().toString().trim();
String PersonalContact = information_crimes_edt.getText().toString().trim();
String CrimesList = spinner.getSelectedItem().toString();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("CrimeContact", contact);
params.put("CrimeInformation", PersonalContact);
params.put("CrimeDate", CrimesList);
params.put("photo",selectedFilePath);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
而且這是在服務器端的代碼,以將圖像上傳至服務器(使用Asp.net和C#)。但我有沒有把圖像和它在這個方法
SaveImage(ImagePic,ImageName);
下面的名字是代碼:
public partial class PoliceApp_ImageUploadaspx : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string ImagePic= "";
string ImageName= "";
SaveImage(ImagePic,ImageName);
}
public bool SaveImage(string ImgStr, string ImgName)
{
String path = HttpContext.Current.Server.MapPath("~/ImageStorage"); //Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist
}
string imageName = ImgName + ".jpg";
//set the image path
string imgPath = Path.Combine(path, imageName);
byte[] imageBytes = Convert.FromBase64String(ImgStr);
File.WriteAllBytes(imgPath, imageBytes);
return true;
}
}
這不是一種傳輸圖像數據的非常有效的方法。 Base64將每組三個字節編碼爲四個字節,再加上一些額外的填充以確保它是4的倍數。這意味着大小爲n的字符串的base-64表示的大小爲:ceil(n/3)* 4或大約30%的額外大小。 –
我想補充Brian的評論。您可以將原始圖像數據放入POST主體,然後在C#中使用context.Request.InputStream訪問原始數據。另一個需要注意的是許多服務器限制了請求URL的長度。所以如果你的圖像變得太大,你將被迫切換到這種方法。 – Licht