Android上传文件到服务器(1)
来源:互联网 发布:彩虹六号围攻优化 编辑:程序博客网 时间:2024/06/03 12:51
Android客户端经常有需要上传文件到服务器,国内的方法一般都是用非常底层的东西,创建一个HttpURLConnection,然后读取文件流,写到connection里,比如这个网址http://www.cnblogs.com/greatverve/archive/2011/12/23/android-upload.html上传文件:
package com.spring.sky.image.upload.network;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.UUID;import android.util.Log;/** * * 上传工具类 * @author spring sky * Email:vipa1888@163.com * QQ:840950105 * MyName:石明政 */public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10*1000; //超时时间 private static final String CHARSET = "utf-8"; //设置编码 /** * android上传文件到服务器 * @param file 需要上传的文件 * @param RequestURL 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file,String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); //边界标识 随机生成 String PREFIX = "--" , LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; //内容类型 try { URL url = new URL(RequestURL); 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); if(file!=null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END); sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END); sb.append(LINE_END); 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(LINE_END.getBytes()); byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 * 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e(TAG, "response code:"+res);// if(res==200)// { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1= new StringBuffer(); int ss ; while((ss=input.read())!=-1) { sb1.append((char)ss); } result = sb1.toString(); Log.e(TAG, "result : "+ result);// }// else{// Log.e(TAG, "request error");// } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }}
下面分享一个高级层面的方法:使用HttpMime上传文件。
public static HttpResponse upload(String url, String fileName, File file) throws ClientProtocolException, IOException{HttpClient client = new DefaultHttpClient();HttpParams httpParam = client.getParams();HttpConnectionParams.setConnectionTimeout(httpParam, 8000);HttpConnectionParams.setSoTimeout(httpParam, 8000);HttpPost request = new HttpPost(url);MultipartEntity entity = new MultipartEntity();entity.addPart(fileName, new FileBody(file));request.setEntity(entity);return client.execute(request, localContext);}
是不是非常简单?
HttpMime的jar包下载地址http://www.java2s.com/Code/Jar/h/Downloadhttpmime412jar.htm, 大家可以导入到项目的Libraries里边,再在Order and Export勾选上里边的HttpMime。
如果想上传文件的时候再POST参数,应该怎么办?没问题,上代码:
public static HttpResponse upload(String url, String fileName, File file, List<NameValuePair> params) throws ClientProtocolException, IOException{HttpClient client = new DefaultHttpClient();HttpParams httpParam = client.getParams();HttpConnectionParams.setConnectionTimeout(httpParam, 8000);HttpConnectionParams.setSoTimeout(httpParam, 8000);HttpPost request = new HttpPost(url);MultipartEntity entity = new MultipartEntity();entity.addPart(fileName, new FileBody(file));if (null != params) {for (int i = 0; i < params.size(); i++) {BasicNameValuePair param = (BasicNameValuePair) params.get(i);entity.addPart(param.getName(),new StringBody(param.getValue()));}}request.setEntity(entity);return client.execute(request, localContext);}
- Android上传文件到服务器(1)
- android文件上传到服务器
- android上传文件到服务器
- android文件上传到服务器
- android 上传文件到服务器
- android 文件上传到服务器
- Android上传文件到服务器
- Android上传文件到服务器
- android上传文件到服务器
- android上传文件到服务器
- android上传文件到服务器
- [android] 文件上传到服务器
- android -上传文件到服务器
- android上传文件到服务器
- android,上传文件到服务器
- Android -- 文件上传到服务器
- Android上传文件到服务器
- android上传文件到服务器
- C++中#include<windows.h>相关说明
- hdu 1501 基本搜索深搜
- socket 五种模型理解之三---------重叠I/O模型(1.事件通知形式)
- 使用AngularJS开发中的几个问题
- QT 利用QSplitter 分割区域, 并添加QScrollArea 滚动区域,滚动条
- Android上传文件到服务器(1)
- 修改Linux命令提示符
- HQL的使用整理
- LeetCode-Recover Binary Search Tree
- nyoj-14-会场安排问题
- cocos2d-x 多层背景滚动效果
- UIActionsheet 自带遮罩效果
- DataLib.PRG -- VFP 数据基础函数库
- C# String.Format 数字格式化输出