android文件上传到服务器
16lz
2021-01-23
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--" , LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
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: text/plain; charset=" + CHARSET+LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if(files!=null){
int i = 0;
for (Map.Entry<String, File> file: files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file"+(i++)+"\"; filename=\""+file.getKey()+"\""+LINEND);
sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
}
//请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
//得到响应码
int res = conn.getResponseCode();
InputStream in = null;
if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
return in == null ? null : in.toString();
}
foreach($_FILES as $v){
copy($v[tmp_name], $v[name]);
}
}
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--" , LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
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: text/plain; charset=" + CHARSET+LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if(files!=null){
int i = 0;
for (Map.Entry<String, File> file: files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file"+(i++)+"\"; filename=\""+file.getKey()+"\""+LINEND);
sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
}
//请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
//得到响应码
int res = conn.getResponseCode();
InputStream in = null;
if (res == 200) {
in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
return in == null ? null : in.toString();
}
最简单的PHP测试代码:
foreach($_FILES as $v){
copy($v[tmp_name], $v[name]);
}
}
参考自 Android中发送Http请求实例(包括文件上传、servlet接收) ,修复了几个问题:
1 多文件上传 file"+(i++)+"
2 返回的错误
另外还可以看看这个(我没测试) android 文件上传的类--完整 可以直接被调用的
这有一个从协议上分析的,比较牛叉:Android下的应用编程——用HTTP协议实现文件上传功能
原创内容如转载请注明:来自 阿权的书房 <script> //<![cdata[ document.write("<br />本帖地址:<a href=\""+window.location+"\">"+window.location+"</a>"); //]]> </script>
本帖地址:http://www.aslibra.com/blog/post/android-upload-files-to-server.php
http 上传文件的方法
- 1./**
- 2.*
- 3.*sendMultipartDataToHttpServer
- 4.*使用post方法请求web服务器,并且当表单数据为:multipart/form-data格式。http请求使用{@link#HTTP_ENCODING}编码<br/>
- 5.*返回json数据,支持文件名中文上传和多文件上传,不支持断点上传,要正确编码服务端返回{@link#HTTP_ENCODING}编码<br/>
- 6.*@paramurl
- 7.*@paramfiles文件表单域
- 8.*@paramfields非文件表单域
- 9.*@returnJSONObject
- 10.*@throwsException
- 11.*@exception
- 12.*@since1.0.0
- 13.*/
- 14.publicstaticJSONObjectsendMultipartDataToHttpServer(URLurl,
- 15.finalMap<String,File>files,finalMap<String,String>fields,
- 16.finalUsernamePasswordCredentialscredentials)throwsIOException,JSONException,Exception{
- 17.URLmyurl=null;
- 18.StringqueryString="";
- 19.//其他的表单域
- 20.if(fields!=null){
- 21.for(Map.Entry<String,String>entry:fields.entrySet()){
- 22.queryString+="&"+URLEncoder.encode(entry.getKey(),HTTP_ENCODING)+"="
- 23.+URLEncoder.encode(entry.getValue(),HTTP_ENCODING);
- 24.}
- 25.}
- 26.if(!queryString.equals("")){
- 27.queryString=queryString.replaceFirst("&","?");
- 28.}else{
- 29.}
- 30.
- 31.myurl=newURL(url.getProtocol(),url.getHost(),url.getPort(),url.getPath()
- 32.+queryString);
- 33.HttpURLConnectionconn=(HttpURLConnection)myurl.openConnection();
- 34.conn.setConnectTimeout(UPLOAD_REQUEST_TIMEOUT);
- 35.conn.setRequestMethod(HTTP_METHOD.POST.toString());
- 36.conn.setDoInput(true);
- 37.conn.setDoOutput(true);
- 38.conn.setUseCaches(false);
- 39.
- 40.Stringboundary="laohuidi_"+java.util.UUID.randomUUID().toString()
- 41.+"_laohuidi";
- 42.conn.setRequestProperty(
- 43."Accept",
- 44."image/gif,image/x-xbitmap,image/jpeg,image/pjpeg,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,application/x-shockwave-flash,application/x-quickviewplus,*/*");
- 45.conn.setRequestProperty("keep-alive","300");
- 46.conn.setRequestProperty(
- 47."user-agent",
- 48."Mozilla/5.0(Windows;U;WindowsNT5.2;zh-CN;rv:1.9.1.6)Gecko/20091201Firefox/3.5.6GTB6");
- 49.conn.setRequestProperty("accept-language","zh-cn,zh;q=0.5");
- 50.conn.setRequestProperty("Connection","Keep-Alive");
- 51.conn.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
- 52.
- 53.DataOutputStreamdos=newDataOutputStream(conn.getOutputStream());
- 54.//乱码问题可以试下PrintWriterout=newPrintWriter(new
- 55.//OutputStreamWriter(connection.getOutputStream(),"utf-8"));
- 56.dos=newDataOutputStream(conn.getOutputStream());
- 57.intbytesRead,bytesAvailable,bufferSize;
- 58.byte[]buffer;
- 59.intmaxBufferSize=IO_BUFFER_SIZE;
- 60.Stringtem="";
- 61.if(files!=null)
- 62.for(Map.Entry<String,File>entry:files.entrySet()){
- 63.//分隔符开头
- 64.dos.writeBytes(TWO_HYPHENS+boundary+LINEND);
- 65.//createabufferofmaximumsize
- 66.FileInputStreamfileInputStream=newFileInputStream(entry.getValue());
- 67.bytesAvailable=fileInputStream.available();
- 68.bufferSize=Math.min(bytesAvailable,maxBufferSize);
- 69.buffer=newbyte[bufferSize];
- 70.//readfileandwriteitintoform...
- 71.bytesRead=fileInputStream.read(buffer,0,bufferSize);
- 72.tem=entry.getValue().getName();
- 73.dos.writeBytes("Content-Disposition:form-data;name=\""+entry.getKey()+"\";"+"filename=\"");
- 74.dos.writeUTF(tem);//中文的文件名使用这里
- 75.dos.writeBytes("\""+LINEND);
- 76.dos.writeBytes("Content-Type:image/jpg"+LINEND+LINEND);//类型的判断暂时不处理
- 77.while(bytesRead>0){
- 78.dos.write(buffer,0,bufferSize);
- 79.bytesAvailable=fileInputStream.available();
- 80.bufferSize=Math.min(bytesAvailable,maxBufferSize);
- 81.bytesRead=fileInputStream.read(buffer,0,bufferSize);
- 82.}
- 83.//closestreams
- 84.fileInputStream.close();
- 85.dos.writeBytes(LINEND);
- 86.}
- 87.//http结束符
- 88.dos.writeBytes(TWO_HYPHENS+boundary+TWO_HYPHENS);
- 89.dos.writeBytes(LINEND);
- 90.
- 91.dos.flush();
- 92.dos.close();
- 93.//返回类型
- 94.StringresponseType=conn.getHeaderField("Content-Type");
- 95.//正常返回而且必须为json类型
- 96.if(conn.getResponseCode()==HttpURLConnection.HTTP_OK
- 97.&&responseType!=null
- 98.&&responseType.indexOf(HTTP_JSON_TYPE)>=0){
- 99.responseType=(convertStreamToString(conn.getInputStream()));
- 100.
- 101.}else{
- 102.responseType="{}";
- 103.}
- 104.try{conn.disconnect();}catch(Exceptione){}
- 105.returnnewJSONObject(responseType);
- 106.}
更多相关文章
- wzplayer for android V1.5.3 (新增YUV文件播放)
- Android解析自定义xml文件(方案一)
- Android客制化------开机拷贝文件到内置存储
- android log日志文件输出
- android按行读取文件内容的几个方法
- android 文件 修改权限
- android 打开不同文件工具类
- 使用命令行ls命令的Android文件浏览控件,适合于root过的设备,可以