http协议上传文件一般最大是2M,比较适合上传小于两M的文件
 
[代码] [Java]代码
 
001import java.io.File; 
002import java.io.FileInputStream; 
003import java.io.FileNotFoundException; 
004import java.io.InputStream; 
005
006/**
007* 上传的文件
008*/ 
009public class FormFile { 
010/** 上传文件的数据 */ 
011private byte[] data; 
012private InputStream inStream; 
013private File file; 
014/** 文件名称 */ 
015private String filname; 
016/** 请求参数名称*/ 
017private String parameterName; 
018/** 内容类型 */ 
019private String contentType = "application/octet-stream"; 
020/**
021*
022* @param filname 文件名称
023* @param data 上传的文件数据
024* @param parameterName 参数
025* @param contentType 内容类型
026*/ 
027public FormFile(String filname, byte[] data, String parameterName, String contentType) { 
028this.data = data; 
029this.filname = filname; 
030this.parameterName = parameterName; 
031if(contentType!=null) this.contentType = contentType; 
032}
033/**
034*
035* @param filname 文件名
036* @param file 上传的文件
037* @param parameterName 参数
038* @param contentType 内容内容类型
039*/ 
040public FormFile(String filname, File file, String parameterName, String contentType) { 
041this.filname = filname; 
042this.parameterName = parameterName; 
043this.file = file; 
044try { 
045this.inStream = new FileInputStream(file); 
046} catch (FileNotFoundException e) { 
047e.printStackTrace();
048}
049if(contentType!=null) this.contentType = contentType; 
050}
051
052public File getFile() { 
053return file; 
054}
055
056public InputStream getInStream() { 
057return inStream; 
058}
059
060public byte[] getData() { 
061return data; 
062}
063
064public String getFilname() { 
065return filname; 
066}
067
068public void setFilname(String filname) { 
069this.filname = filname; 
070}
071
072public String getParameterName() { 
073return parameterName; 
074}
075
076public void setParameterName(String parameterName) { 
077this.parameterName = parameterName; 
078}
079
080public String getContentType() { 
081return contentType; 
082}
083
084public void setContentType(String contentType) { 
085this.contentType = contentType; 
086}
087
088}
089
090/**
091* 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
092* <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">
093<INPUT TYPE="text" NAME="name">
094<INPUT TYPE="text" NAME="id">
095<input type="file" name="imagefile"/>
096<input type="file" name="zip"/>
097</FORM>
098* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
099* @param params 请求参数 key为参数名,value为参数值
100* @param file 上传文件
101*/ 
102public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{ 
103final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线 
104final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志 
105
106int fileDataLength = 0; 
107for(FormFile uploadFile : files){//得到文件类型数据的总长度 
108StringBuilder fileExplain = new StringBuilder(); 
109fileExplain.append("--"); 
110fileExplain.append(BOUNDARY);
111fileExplain.append("\r\n");
112fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
113fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); 
114fileExplain.append("\r\n");
115fileDataLength += fileExplain.length(); 
116if(uploadFile.getInStream()!=null){ 
117fileDataLength += uploadFile.getFile().length(); 
118}else{
119fileDataLength += uploadFile.getData().length; 
120}
121}
122StringBuilder textEntity = new StringBuilder(); 
123for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据 
124textEntity.append("--"); 
125textEntity.append(BOUNDARY);
126textEntity.append("\r\n");
127textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n"); 
128textEntity.append(entry.getValue());
129textEntity.append("\r\n");
130}
131//计算传输给服务器的实体数据总长度 
132int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length; 
133
134URL url = new URL(path); 
135int port = url.getPort()==-1 ? 80 : url.getPort(); 
136Socket socket = new Socket(InetAddress.getByName(url.getHost()), port); 
137OutputStream outStream = socket.getOutputStream(); 
138//下面完成HTTP请求头的发送 
139String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n"; 
140outStream.write(requestmethod.getBytes());
141String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
142outStream.write(accept.getBytes());
143String language = "Accept-Language: zh-CN\r\n"; 
144outStream.write(language.getBytes());
145String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n"; 
146outStream.write(contenttype.getBytes());
147String contentlength = "Content-Length: "+ dataLength + "\r\n"; 
148outStream.write(contentlength.getBytes());
149String alive = "Connection: Keep-Alive\r\n"; 
150outStream.write(alive.getBytes());
151String host = "Host: "+ url.getHost() +":"+ port +"\r\n"; 
152outStream.write(host.getBytes());
153//写完HTTP请求头后根据HTTP协议再写一个回车换行 
154outStream.write("\r\n".getBytes());
155//把所有文本类型的实体数据发送出来 
156outStream.write(textEntity.toString().getBytes());
157//把所有文件类型的实体数据发送出来 
158for(FormFile uploadFile : files){ 
159StringBuilder fileEntity = new StringBuilder(); 
160fileEntity.append("--"); 
161fileEntity.append(BOUNDARY);
162fileEntity.append("\r\n");
163fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
164fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n"); 
165outStream.write(fileEntity.toString().getBytes());
166if(uploadFile.getInStream()!=null){ 
167byte[] buffer = new byte[1024]; 
168int len = 0; 
169while((len = uploadFile.getInStream().read(buffer, 0,1024))!=-1){ 
170outStream.write(buffer, 0, len); 
171}
172uploadFile.getInStream().close();
173}else{
174outStream.write(uploadFile.getData(), 0, uploadFile.getData().length); 
175}
176outStream.write("\r\n".getBytes());
177}
178//下面发送数据结束标志,表示数据已经结束 
179outStream.write(endline.getBytes());
180
181BufferedReader reader = new BufferedReader(newInputStreamReader(socket.getInputStream())); 
182if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
183return false; 
184}
185outStream.flush();
186outStream.close();
187reader.close();
188socket.close();
189return true; 
190}
191
192/**
193* 提交数据到服务器 
194* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
195* @param params 请求参数 key为参数名,value为参数值 
196* @param file 上传文件 
197*/ 
198public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{ 
199return post(path, params, new FormFile[]{file}); 
200}

Android用http协议上传文件的更多相关文章

  1. Android端通过HttpURLConnection上传文件到服务器

    Android端通过HttpURLConnection上传文件到服务器 一:实现原理 最近在做Android客户端的应用开发,涉及到要把图片上传到后台服务器中,自己选择了做Spring3 MVC HT ...

  2. Android端通过HttpURLConnection上传文件到server

    Android端通过HttpURLConnection上传文件到server 一:实现原理 近期在做Androidclient的应用开发,涉及到要把图片上传到后台server中.自己选择了做Sprin ...

  3. c++使用http协议上传文件到七牛云服务器

    使用c++ http协议上传文件到七牛服务器时,比较搞的一点就是header的设置: "Content-Type:multipart/form-data;boundary=xxx" ...

  4. http 协议上传文件multipart form-data boundary 说明--转载

    原文地址:http://xixinfei.iteye.com/blog/2002017 含义 ENCTYPE="multipart/form-data" 说明: 通过 http 协 ...

  5. 通过HTTP协议上传文件

         HTTP是很常见的协议,虽然用得很多,但对细节的了解却是很浅,这回通过向服务端上传文件信息来理解细节.网络库的选择:1.WinHTTP是windows下常用的库:2.CURL是广受喜爱的开源 ...

  6. android 使用AsyncHttpClient框架上传文件以及使用HttpURLConnection下载文件

    AsyncHttpClient开源框架android-async-http还是非常方便的. AsyncHttpClient该类通经常使用在android应用程序中创建异步GET, POST, PUT和 ...

  7. java http工具类和HttpUrlConnection上传文件分析

    利用java中的HttpUrlConnection上传文件,我们其实只要知道Http协议上传文件的标准格式.那么就可以用任何一门语言来模拟浏览器上传文件.下面有几篇文章从http协议入手介绍了java ...

  8. HTTP协议上传boundary确定&下载content-disposition理解

    HTTP协议上传文件-协议 上传文件需要将form标签 的 ENCTYPE 属性设置为 multipart/form-data属性, 与 application/x-www-form-urlencod ...

  9. libcurl上传文件,添加自定义头

    原文  http://www.cnblogs.com/meteoric_cry/p/4285881.html 主题 curl libcurl参数很多,一不小心就容易遇到问题.曾经就遇到过一个很蛋疼的问 ...

随机推荐

  1. ReactNative-闪退日志集成

    根据现实情况,先虚拟个场景 客户:喂,小王,上周发布的新版本,用着用着闪退了呢,是不是有什么问题? 小王:奥?主任,能说一下进行了那些操作吗? 客户:具体的我也不是很清楚,下面具体使用的人反应上来的, ...

  2. Windows xp/2003 中安装虚拟网卡 Microsoft Loopback Adapter

    方法 1 (命令行下安装)devcon.exe install %windir%\inf\netloop.inf *msloop 类似于以下输出表示安装成功: Device node created. ...

  3. KD100遥控生成仪

    KD100是KEYDIY公司开发的一个强大的车用/民用遥控器生成工具,所生成的遥控器都具备不重码,质量稳定的特点. 通过采用英飞凌和NXP等公司开发的超级芯片,KD100巧妙的解决了各类型遥控器的兼容 ...

  4. VS2010 + IDA SDK 搭建IDA Plugin开发环境

    http://www.h4ck.org.cn/2011/11/vs2010-idasdk6-2-ida-plugin-development/ 1. 执行菜单的File->New->Pro ...

  5. ssl 复制

    http://www.ttlsa.com/mysql/mysql-replication-base-on-ssl/ http://www.tuicool.com/articles/mi2iaq htt ...

  6. jdbcTemplate:包含占位符的SQL无法打印参数信息

    网上的解决方案是在log4j设置以下参数:(如:http://my.oschina.net/wamdy/blog/468491) log4j.logger.org.springframework.jd ...

  7. [转] NSMapTable 不只是一个能放weak指针的 NSDictionary

    NSMapTable 不只是一个能放weak指针的 NSDictionary NSMapTable是早在Mac OS X 10.5(Leopard)的引入集合类.乍一看,这似乎是作为一个替换NSDic ...

  8. OpenCV学习(8) 分水岭算法(2)

        现在我们看看OpenCV中如何使用分水岭算法.     首先我们打开一副图像:    // 打开另一幅图像   cv::Mat    image= cv::imread("../to ...

  9. DGN格式转化为shp格式 【转】

    其实本来,我就是需要把一个autocad的dwg/dgn格式的东西导入到google earth里面:但是首先我对dwg/dgn格式的东西根本就不熟:其次我拿到的dwg/dgn格式文件是用的HK80 ...

  10. Servlet学习笔记(二):表单数据

    很多情况下,需要传递一些信息,从浏览器到 Web 服务器,最终到后台程序.浏览器使用两种方法可将这些信息传递到 Web 服务器,分别为 GET 方法和 POST 方法. 1.GET 方法:GET 方法 ...