安卓客户端,与上传图片有关的代码
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--";
try {
ByteArrayOutputStream bitmapByteOutput=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,bitmapByteOutput); //bitmap是要上传的图片
String beginLine=BOUNDARY+"\r\n";
String param="Content-Disposition=from-data&name=imageFile&fileName=imageFile&Content-Type=image/jpeg\r\n";
String endLine=BOUNDARY+PREFIX+"\r\n";
byte[] bitmapByte=bitmapByteOutput.toByteArray();
URL url = new URL("http://192.168.1.102:63116/UploadTest/UploadImage");
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "multipart/from-data");
con.setRequestProperty("Content-Length",String.valueOf( beginLine.getBytes().length+param.getBytes().length+bitmapByte.length+endLine.getBytes().length));
OutputStream out=con.getOutputStream();
out.write(beginLine.getBytes());
out.write(param.getBytes());
out.write(bitmapByte);
out.write(endLine.getBytes());
out.flush();
if(con.getResponseCode()==200)
{
InputStream input=con.getInputStream();
ByteArrayOutputStream output=new ByteArrayOutputStream();
int b;
while((b=input.read())!=-1)
output.write(b);
String response=output.toString();
input.close();
output.close();
con.disconnect();
}
}
catch(Exception e)
{
Log.e("this","上传图片的时候出错了"+e);
}
我的ASP.NET MVC服务端与接收图片有关的代码,是controller中的一个action
public ActionResult uploadImage(HttpPostedFileBase imageFile)
{
try
{
string name = imageFile.FileName;
string fileName = Path.GetFileName(name);
string filePath = Server.MapPath("/ImageTest/" + fileName);
imageFile.SaveAs(filePath);
return Content("success");
}
catch (Exception ex)
{
return Content("fail"+ex);
}
}
现在客户端接收到服务端返回错误的信息(上面asp.net mvc若出错了会把出错信息ex返回给客户端),就是NullReferenceException,未将对象实例设置到对象引用。指的应该是传进来的参数HttpPostedFileBase对象为null,那么这个是怎么解决呢?
应该是是这段安卓上传图片的代码有问题,但总是找不到问题所在,求指点