android 端代码
package com.example.uploadfile; import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map; public class PostFile {
static String BOUNDARY = java.util.UUID.randomUUID().toString();
static String PREFIX = "--";
static String LINEND = "\r\n";
static String MULTIPART_FROM_DATA = "multipart/form-data";
static String CHARSET = "UTF-8";
static String result =null;
static int SO_TIMEOUT=5*1000; //上传代码,第一个参数,为要使用的URL,第二个参数,为表单内容,第三个参数为要上传的文件,可以上传多个文件,这根据需要页定
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {
try{
URL url =new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(SO_TIMEOUT);
conn.setConnectTimeout(SO_TIMEOUT);
conn.setDoInput(true);// 允许输入流
conn.setDoOutput(true);// 允许输出流
conn.setUseCaches(false);// 不允许使用缓存
conn.setRequestMethod("POST");// 请求方式
conn.setRequestProperty("Charset",CHARSET);// 设置编码
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("Charsert", CHARSET);
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +";boundary="+ BOUNDARY);
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos =new DataOutputStream(
conn.getOutputStream());
StringBuffer sb =new StringBuffer();
for(Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() +"\""+ LINEND);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
if(files!=null){
for (Map.Entry<String, File> file : files.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\""+file.getKey()+"\"; filename=\""+ file.getValue() +"\""+ LINEND);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND);
sb.append(LINEND); dos.write(sb.toString().getBytes());
InputStream is =new FileInputStream(file.getValue());
byte[] bytes =new byte[1024];
int len = 0;
while((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINEND.getBytes());
}
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res= conn.getResponseCode(); InputStream input = conn.getInputStream();
StringBuffer sb1 =new StringBuffer();
int ss;
while((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
}
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
return result;
} /**
* 上传单张图片加参数
*@paramfile 文件
*@paramfileName 服务器接口图片参数名称
*@paramRequestURL 上传URL
*@paramparams 参数
*@return
*/
public static String PostData(File file,String fileName, String RequestURL,Map<String, String> params) { try{
URL url =new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(SO_TIMEOUT);
conn.setConnectTimeout(SO_TIMEOUT);
conn.setDoInput(true);// 允许输入流
conn.setDoOutput(true);// 允许输出流
conn.setUseCaches(false);// 不允许使用缓存
conn.setRequestMethod("POST");// 请求方式
conn.setRequestProperty("Charset",CHARSET);// 设置编码
conn.setRequestProperty("connection","keep-alive");
conn.setRequestProperty("Charsert", CHARSET);
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA +";boundary="+ BOUNDARY); if(file !=null) {
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos =new DataOutputStream(
conn.getOutputStream());
StringBuffer sb =new StringBuffer(); for(Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() +"\""+ LINEND);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
} sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\""+fileName+"\"; filename=\""+ file.getName() +"\""+ LINEND);
sb.append("Content-Type: application/octet-stream; charset="+CHARSET+ LINEND);
sb.append(LINEND); dos.write(sb.toString().getBytes());
InputStream is =new FileInputStream(file);
byte[] bytes =new byte[1024];
int len = 0;
while((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINEND.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res= conn.getResponseCode(); InputStream input = conn.getInputStream();
StringBuffer sb1 =new StringBuffer();
int ss;
while((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
}
}catch(MalformedURLException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}
return result;
}
}
package com.example.uploadfile; import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map; import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button; public class MainActivity extends Activity {
Button btn_upload,btn_upload1,btn_upload2,btn_upload3;
Map<String, File> files;
Map<String, String> params;
String result="";
private ProgressDialog pd;
private String httpUrl="http://192.168.1.136/api.ashx";
private String httpUrl1="http://192.168.1.136/upFiles.ashx";
String path=Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/IMG_20160103_122157.jpg";
//String path=Environment.getExternalStorageDirectory().getPath()+"/DCIM/P60131-103130.JPG"; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_upload=(Button)this.findViewById(R.id.btn_upload);
btn_upload1=(Button)this.findViewById(R.id.btn_upload1);
btn_upload2=(Button)this.findViewById(R.id.btn_upload2);
btn_upload3=(Button)this.findViewById(R.id.btn_upload3); btn_upload.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("正在上传...");
pd.show();
params=new HashMap<String, String>();
params.put("pictureName","aaaa.jpg");
files=new HashMap<String, File>();
files.put("picturePath", new File(path));
new Thread(new Runnable() {
@Override
public void run() {
try {
result=PostFile.post(httpUrl, params, files);
} catch (IOException e) {
e.printStackTrace();
}
Message msg=handler.obtainMessage();
msg.what=1;
handler.sendMessage(msg);
}
}).start();
}
}); btn_upload1.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("正在上传...");
pd.show();
params=new HashMap<String, String>();
params.put("pictureName","aaaa.jpg");
files=new HashMap<String, File>();
files.put("picturePath", new File(path));
new Thread(new Runnable() {
@Override
public void run() {
result=PostFile.PostData(new File(path), "picturePath", httpUrl, params);
Message msg=handler.obtainMessage();
msg.what=1;
handler.sendMessage(msg);
}
}).start();
}
}); btn_upload2.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("正在上传...");
pd.show();
Bitmap bitmap=ImageUtils.imageToBitmap(path);
String imageBase64=ImageUtils.convertIconToString(bitmap);
params=new HashMap<String, String>();
params.put("picturePath",imageBase64);
files=new HashMap<String, File>();
new Thread(new Runnable() { @Override
public void run() {
try {
result=PostFile.post(httpUrl1, params,files);
} catch (IOException e) {
e.printStackTrace();
}
Message msg=handler.obtainMessage();
msg.what=1;
handler.sendMessage(msg);
}
}).start();
}
}); btn_upload3.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) { }
}); } private Handler handler=new Handler(){ @Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
pd.dismiss();
Log.e("result", result);
} };
}
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 服务 端代码
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(, "" + context.Request.Files.Count));
return;
}
if (String.IsNullOrEmpty(file.FileName))
{
context.Response.Write(getGson(, "" + 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(, "" + 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;
}
} }
}