andrid 上传图片 asp.net 后台接收并保存
android 端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.example.uploadfile; 2 3 import java.io.DataOutputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.net.HttpURLConnection; 9 import java.net.MalformedURLException; 10 import java.net.URL; 11 import java.util.Map; 12 13 public class PostFile { 14 static String BOUNDARY = java.util.UUID.randomUUID().toString(); 15 static String PREFIX = "--"; 16 static String LINEND = "\r\n"; 17 static String MULTIPART_FROM_DATA = "multipart/form-data"; 18 static String CHARSET = "UTF-8"; 19 static String result =null; 20 static int SO_TIMEOUT=5*1000; 21 22 //上传代码,第一个参数,为要使用的URL,第二个参数,为表单内容,第三个参数为要上传的文件,可以上传多个文件,这根据需要页定 23 public static String post(String actionUrl, Map<String, String> params, 24 Map<String, File> files) throws IOException { 25 try{ 26 URL url =new URL(actionUrl); 27 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 28 conn.setReadTimeout(SO_TIMEOUT); 29 conn.setConnectTimeout(SO_TIMEOUT); 30 conn.setDoInput(true);// 允许输入流 31 conn.setDoOutput(true);// 允许输出流 32 conn.setUseCaches(false);// 不允许使用缓存 33 conn.setRequestMethod("POST");// 请求方式 34 conn.setRequestProperty("Charset",CHARSET);// 设置编码 35 conn.setRequestProperty("connection","keep-alive"); 36 conn.setRequestProperty("Charsert", CHARSET); 37 conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +";boundary="+ BOUNDARY); 38 /** 39 * 当文件不为空,把文件包装并且上传 40 */ 41 DataOutputStream dos =new DataOutputStream( 42 conn.getOutputStream()); 43 StringBuffer sb =new StringBuffer(); 44 for(Map.Entry<String, String> entry : params.entrySet()) { 45 sb.append(PREFIX); 46 sb.append(BOUNDARY); 47 sb.append(LINEND); 48 sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() +"\""+ LINEND); 49 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND); 50 sb.append(LINEND); 51 sb.append(entry.getValue()); 52 sb.append(LINEND); 53 } 54 if(files!=null){ 55 for (Map.Entry<String, File> file : files.entrySet()) { 56 sb.append(PREFIX); 57 sb.append(BOUNDARY); 58 sb.append(LINEND); 59 /** 60 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 61 * filename是文件的名字,包含后缀名的 比如:abc.png 62 */ 63 sb.append("Content-Disposition: form-data; name=\""+file.getKey()+"\"; filename=\""+ file.getValue() +"\""+ LINEND); 64 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND); 65 sb.append(LINEND); 66 67 dos.write(sb.toString().getBytes()); 68 InputStream is =new FileInputStream(file.getValue()); 69 byte[] bytes =new byte[1024]; 70 int len = 0; 71 while((len = is.read(bytes)) != -1) { 72 dos.write(bytes, 0, len); 73 } 74 is.close(); 75 dos.write(LINEND.getBytes()); 76 } 77 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); 78 dos.write(end_data); 79 dos.flush(); 80 /** 81 * 获取响应码 200=成功 当响应成功,获取响应的流 82 */ 83 int res= conn.getResponseCode(); 84 85 InputStream input = conn.getInputStream(); 86 StringBuffer sb1 =new StringBuffer(); 87 int ss; 88 while((ss = input.read()) != -1) { 89 sb1.append((char) ss); 90 } 91 result = sb1.toString(); 92 } 93 }catch(MalformedURLException e) { 94 e.printStackTrace(); 95 }catch(IOException e) { 96 e.printStackTrace(); 97 } 98 return result; 99 } 100 101 102 /** 103 * 上传单张图片加参数 104 *@paramfile 文件 105 *@paramfileName 服务器接口图片参数名称 106 *@paramRequestURL 上传URL 107 *@paramparams 参数 108 *@return 109 */ 110 public static String PostData(File file,String fileName, String RequestURL,Map<String, String> params) { 111 112 try{ 113 URL url =new URL(RequestURL); 114 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 115 conn.setReadTimeout(SO_TIMEOUT); 116 conn.setConnectTimeout(SO_TIMEOUT); 117 conn.setDoInput(true);// 允许输入流 118 conn.setDoOutput(true);// 允许输出流 119 conn.setUseCaches(false);// 不允许使用缓存 120 conn.setRequestMethod("POST");// 请求方式 121 conn.setRequestProperty("Charset",CHARSET);// 设置编码 122 conn.setRequestProperty("connection","keep-alive"); 123 conn.setRequestProperty("Charsert", CHARSET); 124 conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +";boundary="+ BOUNDARY); 125 126 if(file !=null) { 127 /** 128 * 当文件不为空,把文件包装并且上传 129 */ 130 DataOutputStream dos =new DataOutputStream( 131 conn.getOutputStream()); 132 StringBuffer sb =new StringBuffer(); 133 134 for(Map.Entry<String, String> entry : params.entrySet()) { 135 sb.append(PREFIX); 136 sb.append(BOUNDARY); 137 sb.append(LINEND); 138 sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() +"\""+ LINEND); 139 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND); 140 sb.append(LINEND); 141 sb.append(entry.getValue()); 142 sb.append(LINEND); 143 } 144 145 sb.append(PREFIX); 146 sb.append(BOUNDARY); 147 sb.append(LINEND); 148 /** 149 * 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 150 * filename是文件的名字,包含后缀名的 比如:abc.png 151 */ 152 sb.append("Content-Disposition: form-data; name=\""+fileName+"\"; filename=\""+ file.getName() +"\""+ LINEND); 153 sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND); 154 sb.append(LINEND); 155 156 dos.write(sb.toString().getBytes()); 157 InputStream is =new FileInputStream(file); 158 byte[] bytes =new byte[1024]; 159 int len = 0; 160 while((len = is.read(bytes)) != -1) { 161 dos.write(bytes, 0, len); 162 } 163 is.close(); 164 dos.write(LINEND.getBytes()); 165 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND) 166 .getBytes(); 167 dos.write(end_data); 168 dos.flush(); 169 /** 170 * 获取响应码 200=成功 当响应成功,获取响应的流 171 */ 172 int res= conn.getResponseCode(); 173 174 InputStream input = conn.getInputStream(); 175 StringBuffer sb1 =new StringBuffer(); 176 int ss; 177 while((ss = input.read()) != -1) { 178 sb1.append((char) ss); 179 } 180 result = sb1.toString(); 181 } 182 }catch(MalformedURLException e) { 183 e.printStackTrace(); 184 }catch(IOException e) { 185 e.printStackTrace(); 186 } 187 return result; 188 } 189 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.example.uploadfile; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.HashMap; 6 import java.util.Map; 7 8 import android.app.Activity; 9 import android.app.ProgressDialog; 10 import android.graphics.Bitmap; 11 import android.os.Bundle; 12 import android.os.Environment; 13 import android.os.Handler; 14 import android.os.Message; 15 import android.util.Log; 16 import android.view.View; 17 import android.widget.Button; 18 19 20 public class MainActivity extends Activity { 21 Button btn_upload,btn_upload1,btn_upload2,btn_upload3; 22 Map<String, File> files; 23 Map<String, String> params; 24 String result=""; 25 private ProgressDialog pd; 26 private String httpUrl="http://192.168.1.136/api.ashx"; 27 private String httpUrl1="http://192.168.1.136/upFiles.ashx"; 28 String path=Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/IMG_20160103_122157.jpg"; 29 //String path=Environment.getExternalStorageDirectory().getPath()+"/DCIM/P60131-103130.JPG"; 30 31 @Override 32 protected void onCreate(Bundle savedInstanceState) { 33 super.onCreate(savedInstanceState); 34 setContentView(R.layout.activity_main); 35 btn_upload=(Button)this.findViewById(R.id.btn_upload); 36 btn_upload1=(Button)this.findViewById(R.id.btn_upload1); 37 btn_upload2=(Button)this.findViewById(R.id.btn_upload2); 38 btn_upload3=(Button)this.findViewById(R.id.btn_upload3); 39 40 41 btn_upload.setOnClickListener(new View.OnClickListener() { 42 43 @Override 44 public void onClick(View v) { 45 pd = new ProgressDialog(MainActivity.this); 46 pd.setMessage("正在上传..."); 47 pd.show(); 48 params=new HashMap<String, String>(); 49 params.put("pictureName","aaaa.jpg"); 50 files=new HashMap<String, File>(); 51 files.put("picturePath", new File(path)); 52 new Thread(new Runnable() { 53 @Override 54 public void run() { 55 try { 56 result=PostFile.post(httpUrl, params, files); 57 } catch (IOException e) { 58 e.printStackTrace(); 59 } 60 Message msg=handler.obtainMessage(); 61 msg.what=1; 62 handler.sendMessage(msg); 63 } 64 }).start(); 65 } 66 }); 67 68 btn_upload1.setOnClickListener(new View.OnClickListener() { 69 70 @Override 71 public void onClick(View v) { 72 pd = new ProgressDialog(MainActivity.this); 73 pd.setMessage("正在上传..."); 74 pd.show(); 75 params=new HashMap<String, String>(); 76 params.put("pictureName","aaaa.jpg"); 77 files=new HashMap<String, File>(); 78 files.put("picturePath", new File(path)); 79 new Thread(new Runnable() { 80 @Override 81 public void run() { 82 result=PostFile.PostData(new File(path), "picturePath", httpUrl, params); 83 Message msg=handler.obtainMessage(); 84 msg.what=1; 85 handler.sendMessage(msg); 86 } 87 }).start(); 88 } 89 }); 90 91 btn_upload2.setOnClickListener(new View.OnClickListener() { 92 93 @Override 94 public void onClick(View v) { 95 pd = new ProgressDialog(MainActivity.this); 96 pd.setMessage("正在上传..."); 97 pd.show(); 98 Bitmap bitmap=ImageUtils.imageToBitmap(path); 99 String imageBase64=ImageUtils.convertIconToString(bitmap); 100 params=new HashMap<String, String>(); 101 params.put("picturePath",imageBase64); 102 files=new HashMap<String, File>(); 103 new Thread(new Runnable() { 104 105 @Override 106 public void run() { 107 try { 108 result=PostFile.post(httpUrl1, params,files); 109 } catch (IOException e) { 110 e.printStackTrace(); 111 } 112 Message msg=handler.obtainMessage(); 113 msg.what=1; 114 handler.sendMessage(msg); 115 } 116 }).start(); 117 } 118 }); 119 120 btn_upload3.setOnClickListener(new View.OnClickListener() { 121 122 @Override 123 public void onClick(View v) { 124 125 } 126 }); 127 128 } 129 130 private Handler handler=new Handler(){ 131 132 @Override 133 public void handleMessage(Message msg) { 134 super.handleMessage(msg); 135 pd.dismiss(); 136 Log.e("result", result); 137 } 138 139 }; 140 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.example.uploadfile; import java.io.ByteArrayOutputStream; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.util.Base64; /** * 类 名:ImageUtils * 作 者:Free宇 * 主要功能: * 创建日期 :2016-2-2 下午1:33:19 * 参 数: * 修 改 者: * 修改日期: * 修改内容: */ public class ImageUtils { /*** * 动态设置inSampleSize 倍数 * * @param pathName * 图片路径 * @param reqWidth * 要压缩的宽度 * @param reqHeight * 要压缩的高度 * @return */ public static Bitmap imageToBitmap(String pathName) { // 首先设置 inJustDecodeBounds=true 来获取图片尺寸 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); // 计算 inSampleSize 的值 options.inSampleSize =100; // 根据计算出的 inSampleSize 来解码图片生成Bitmap options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(pathName, options); } /** * 图片转成string * * @param bitmap * @return */ public static String convertIconToString(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream bitmap.compress(CompressFormat.PNG, 100, baos); byte[] appicon = baos.toByteArray();// 转为byte数组 return Base64.encodeToString(appicon, Base64.DEFAULT); } }
asp.net 服务 端代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace uploadFiles { /// <summary> /// api 的摘要说明 /// </summary> public class api : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpPostedFile file = context.Request.Files["picturePath"]; //可以用传入参数命名 //String pictureName = context.Request.Form["pictureName"]; if (file == null) { context.Response.Write(getGson(0, "404" + context.Request.Files.Count)); return; } if (String.IsNullOrEmpty(file.FileName)) { context.Response.Write(getGson(0, "405" + context.Request.Files.Count)); return; } String imagePath = "/upload/" + DateTime.Now.ToString("yyyyMMdd") + "/"; string physicsPath = HttpContext.Current.Server.MapPath("~" + imagePath); if (!System.IO.Directory.Exists(physicsPath)) { System.IO.Directory.CreateDirectory(physicsPath); } //生成新文件名 int index = file.FileName.LastIndexOf("."); string fileExt = file.FileName.Substring(index); string datestring = DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.Millisecond.ToString(); string pictureName = datestring + fileExt; file.SaveAs(physicsPath + pictureName); context.Response.Write(getGson(0, "200" + file.FileName)); } private String getGson(int status,String msg) { String json = "{\"status\": " + status + ",\"msg\": \"" + msg + "\",\"info\":{\"id\":1}}"; return json; } public bool IsReusable { get { return false; } } } }