/**
*
* 转载请标明出处:http://blog.csdn.net/u013598111/article/details/51440346
* @author:【JunTao_sun】
*
*
*/
小文件上传
public class Network_One {
//.*( 二进制流,不知道下载文件类型) application/octet-stream
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 5*1000; //超时时间
private static final String CHARSET = "UTF-8"; //设置编码
public static void fileUpLoad(Map<String, String> params,String fileUrl,
String filePath,Context mContext,String fileName ) {
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
String CONTENT_TYPE = "multipart/form-data"; //内容类型
try {
StringBuilder sb = new StringBuilder();
/**
* 普通的表单数据
*/
for (String key : params.keySet()) {
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + key + "\""
+ "\r\n");
sb.append("\r\n");
sb.append(params.get(key) + "\r\n");
}
File file=new File(filePath);
if(!file.exists()) return;
/**
* 上传文件的头
*/
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\""+fileName
+ "\"; filename=\"" + fileName+ "\"" + "\r\n");
sb.append("Content-Type: image/jpeg" + "\r\n");
sb.append("\r\n");
byte[] headerInfo=sb.toString().getBytes("UTF-8");
byte[] endInfo=("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(fileUrl);
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); //允许输入流
conn.setDoOutput(true); //允许输出流
conn.setUseCaches(false); //不允许使用缓存
conn.setRequestMethod("POST"); //请求方式
conn.setRequestProperty("Charset", CHARSET); //设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
conn.setRequestProperty("Content-Length", String
.valueOf(headerInfo.length + file.length()
+ endInfo.length));
if(filePath!=null)
{
/**
* 当文件不为空,把文件包装并且上传
*/
OutputStream dos = conn.getOutputStream();
InputStream is=new FileInputStream(file);
dos.write(headerInfo);
byte[] bytes = new byte[1024];
int len = 0;
while((len=is.read(bytes))!=-1)
{
dos.write(bytes, 0, len);
}
is.close();
dos.write(endInfo);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
dos.close();
conn.disconnect();
}} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
下面是利用socket 用流的方式上传比较大的文件 :
请求失败 400 的话就是客服端问题,检查请求头的格式,是否有写错的地方。
public static void BigUploader(Map<String, String> params,String fileUrl,
String filePath,Context mContext,String fileName ){
String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\"" + key + "\""
+ "\r\n");
sb.append("\r\n");
sb.append(params.get(key) + "\r\n");
}
File file=new File(filePath);
Log.e("文件是否存在", file.exists()+"");
// if(!file.exists()) return;
/**
* 上传文件的头
*/
sb.append("--" + BOUNDARY + "\r\n");
sb.append("Content-Disposition: form-data; name=\""+file.getName()
+ "\"; filename=\"" + file.getName()+ "\"" + "\r\n");
sb.append("Content-Type: image/jpeg" + "\r\n");
sb.append("\r\n");
try {
byte[] headerInfo=sb.toString().getBytes("UTF-8");
byte[] endInfo=("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
URL url = new URL(fileUrl);
int port=url.getPort()==-1?80:url.getPort();
Socket socket= new Socket(InetAddress.getByName(url.getHost()),port);
// SocketAddress dest = new InetSocketAddress(url.getHost(), url.getPort());
// socket.connect(dest);
OutputStream out=socket.getOutputStream();
PrintStream ps = new PrintStream(out, true, "UTF-8");
// 写出请求头
ps.println("POST " + url.getPath() + " HTTP/1.1");
ps.println("Accept-Language: zh-CN");
ps.println("Content-Type: multipart/form-data; boundary=" + BOUNDARY);
ps.println("Content-Length: "
+ String.valueOf(headerInfo.length + file.length()
+ endInfo.length));
ps.println("Accept: text/html, application/xhtml+xml, application/xml, */*");
ps.println("Host:"+url.getHost()+":"+url.getPort());
ps.println("Connection:keep-Alive");
out.write("\r\n".getBytes("UTF-8"));
out.write(headerInfo);
int len;
byte[] buffer=new byte[1024];
FileInputStream input =new FileInputStream(file);
while ((len=input.read(buffer))!=-1) {
out.write(buffer,0,len);
}
out.write(endInfo);
// out.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.e(TAG, reader.readLine());
Log.e(TAG, reader.readLine());
Log.e(TAG, reader.readLine());
Log.e(TAG, reader.readLine()+);
Log.e(TAG, "succeed-uploader");
input.close();
ps.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}