Android中上传图片到服务端C#接收图
16lz
2021-12-04
Android端
/* 上传文件至Server的方法 */public static String uploadFile(String actionUrl, String newName, Bitmap bitmap){ String end ="\r\n"; String twoHyphens ="--"; String boundary ="*****"; try{ URL url =new URL(actionUrl); HttpURLConnection con=(HttpURLConnection)url.openConnection(); /* 允许Input、Output,不使用Cache */ con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); /* 设置传送的method=POST */ con.setRequestMethod("POST"); /* setRequestProperty */ con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); con.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); /* 设置DataOutputStream */ DataOutputStream ds = new DataOutputStream(con.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; "+ "name=\"file1\";"+"drawingName=\""+ newName +"\""+ end); ds.writeBytes(end); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 80, baos); InputStream isBm = new ByteArrayInputStream(baos.toByteArray()); /* 取得文件的FileInputStream */ // FileInputStream fStream =new FileInputStream(uploadFile); /* 设置每次写入1024bytes */ int bufferSize =1024; byte[] buffer =new byte[bufferSize]; int length =-1; /* 从文件读取数据至缓冲区 */ while((length = isBm.read(buffer)) !=-1){ /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ isBm.close(); ds.flush(); /* 取得Response内容 */ InputStream is = con.getInputStream(); int ch; StringBuffer b =new StringBuffer(); while( ( ch = is.read() ) !=-1 ){ b.append( (char)ch ); } /* 将Response显示于Dialog */ /* 关闭DataOutputStream */ ds.close();
//获取到的响应数据 return b.toString(); } catch(Exception e){ return ""; }
C#服务端
private String getPic(){//此方法名是Android端上传图片中接口地址中使用的
//最主要的代码:HttpContext.Request.InputStream;获取Android中上传的字节流数据 byte[] byts = new byte[HttpContext.Current.Request.InputStream.Length]; HttpContext.Current.Request.InputStream.Read(byts, 0, byts.Length); string req = System.Text.Encoding.Default.GetString(byts); req = HttpContext.Current.Server.UrlDecode(req);return req;//返回给android}
更多相关文章
- mybatisplus的坑 insert标签insert into select无参数问题的解决
- python起点网月票榜字体反爬案例
- Android选项卡(TabWidget)应用
- Android应用程序组件Content Provider在应用程序之间共享数据的
- android SQLite操作
- Android(安卓)设置StatusBar的颜色
- android SQLite操作
- 关于设置线性布局及其他布局的宽高
- Android(安卓)Studio常见布局报错及解决方案