android端:
//android端的网络操作一定要放入线程中
Thread aaa = new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
String fileName="bbb";
picNameId = fileName + "," + Tools.getId();
String str="http://192.168.1.191:8002/Mobile/Mobile_SavePicToLocal?picNameId=" + picNameId + "&sessionId="+ sessionid +"&pNumber=";
try {
URL url=new URL(str);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("FileName", fileName);
connection.setRequestProperty("content-type", "text/html");
//http加入流,可以传任何数据
OutputStream os = connection.getOutputStream();
BufferedOutputStream out = new BufferedOutputStream(os);//从post获取stream
out.write(picData,0,picData.length); //这里写入你的字节数组
out.flush();
InputStreamReader in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
String result = strBuffer.toString(); //返回的字符串数据
} catch (Exception e) {
Log.e("getOutputStream()报错",e.getMessage());
}
}
};
aaa.start();
服务器端代码:
[HttpPost]
public JsonResult Mobile_SavePicToLocal(string picNameId, string sessionId, string pNumber)
{
sessionId = sessionId.Trim();
XmlConfig config = GlobalSettings.GetInstance().GetConfig();
string ip = config.ReadString("userIpPort", "ip");
string port = config.ReadString("userIpPort", "port");
//验证session
string url = "http://" + ip + ":" + port +"/Admin/CheckTokenExpire/?token=" + sessionId + "&ip=&loginType2";
string jsonR = PostDataByUrl(url);
JsonEntity jsEntity = JsonConvert.DeserializeObject<JsonEntity>(jsonR);
if (!jsEntity.Success) {
return Json(new { success = false });
}
string fileName = picNameId + ".jpg";
Stream stream = Request.InputStream; //这一句是关键
long contentLength = stream.Length;
MemoryStream msPic = new MemoryStream();
string currentFilePath = Common.GetSelfPath() + "\\手机图片\\" + jsEntity.User.username + "\\";
if (!Directory.Exists(currentFilePath))
{
Directory.CreateDirectory(currentFilePath);
}
FileStream fileStream = System.IO.File.Create(currentFilePath + @"\" + fileName);
//每次读取的1024个字节
byte[] bytes = new byte[1024];
int numReadByte = 0;
while ((numReadByte = stream.Read(bytes, 0, 1024)) != 0)
{
fileStream.Write(bytes, 0, numReadByte);
msPic.Write(bytes, 0, numReadByte);
}
//关闭流
stream.Close();
fileStream.Close();
msPic.Flush();
msPic.Close();
return Json(new { success = true});
}