formfile文件上传使用示例
package tools;
import java.io.bufferedreader;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.inputstream;
import java.io.inputstreamreader;
import java.io.outputstream;
import java.net.inetaddress;
import java.net.socket;
import java.net.url;
import java.util.map;
import android.util.log;
/**
* 上传的文件
*/
public class formfile {
private final static string logkey = "formfile";
/** 上传文件的数据 */
private byte[] data;
private inputstream instream;
private file file;
/** 文件名称 */
private string filname;
/** 请求参数名称 */
private string parametername;
/** 内容类型 */
private string contenttype = "application/octet-stream";
/**
*
* @param filname
* 文件名称
* @param data
* 上传的文件数据
* @param parametername
* 参数
* @param contenttype
* 内容类型
*/
public formfile(string filname, byte[] data, string parametername,
string contenttype) {
this.data = data;
this.filname = filname;
this.parametername = parametername;
if (contenttype != null)
this.contenttype = contenttype;
}
/**
*
* @param filname
* 文件名
* @param file
* 上传的文件
* @param parametername
* 参数
* @param contenttype
* 内容内容类型
*/
public formfile(string filname, file file, string parametername,
string contenttype) {
this.filname = filname;
this.parametername = parametername;
this.file = file;
try {
this.instream = new fileinputstream(file);
} catch (filenotfoundexception e) {
e.printstacktrace();
}
if (contenttype != null)
this.contenttype = contenttype;
}
public file getfile() {
return file;
}
public inputstream getinstream() {
return instream;
}
public byte[] getdata() {
return data;
}
public string getfilname() {
return filname;
}
public void setfilname(string filname) {
this.filname = filname;
}
public string getparametername() {
return parametername;
}
public void setparametername(string parametername) {
this.parametername = parametername;
}
public string getcontenttype() {
return contenttype;
}
public void setcontenttype(string contenttype) {
this.contenttype = contenttype;
}
private string opertype=null;
public void setoper(string opertype){
this.opertype=opertype;
}
public boolean post(string path, map<string, string> params)
throws exception {
final string boundary = "--------------7da2137580612"; // 数据分隔线
final string endline = "--" + boundary + "--\r\n";// 数据结束标志
int filedatalength = 0;
// 得到文件类型数据的总长度
stringbuilder fileexplain = new stringbuilder();
fileexplain.append("--");
fileexplain.append(boundary);
fileexplain.append("\r\n");
fileexplain.append("content-disposition: form-data;name=\""
+ getparametername() + "\";filename=\"" + getfilname()
+ "\"\r\n");
fileexplain.append("content-type: " + getcontenttype() + "\r\n\r\n");
fileexplain.append("\r\n");
filedatalength += fileexplain.length();
if (getinstream() != null) {
filedatalength += getfile().length();
} else {
filedatalength += getdata().length;
}
stringbuilder textentity = new stringbuilder();
for (map.entry<string, string> entry : params.entryset()) {//构造文本类型参数的实体数据
textentity.append("--");
textentity.append(boundary);
textentity.append("\r\n");
textentity.append("content-disposition: form-data; name=\""
+ entry.getkey() + "\"\r\n\r\n");
textentity.append(entry.getvalue());
textentity.append("\r\n");
}
log.v(logkey, textentity.tostring());
// 计算传输给服务器的实体数据总长度
int datalength = textentity.tostring().getbytes().length
+ filedatalength + endline.getbytes().length;
url url = new url(path);
log.v(logkey, url.tostring());
int port = url.getport() == -1 ? 80 : url.getport();
socket socket = new socket(inetaddress.getbyname(url.gethost()), port);
outputstream outstream = socket.getoutputstream();
// 下面完成http请求头的发送
string requestmethod = "post " + url.getpath()+"?"+opertype + " http/1.1\r\n";
log.v(logkey, requestmethod);
outstream.write(requestmethod.getbytes());
string 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";
outstream.write(accept.getbytes());
string language = "accept-language: zh-cn\r\n";
outstream.write(language.getbytes());
string contenttype = "content-type: multipart/form-data; boundary="
+ boundary + "\r\n";
outstream.write(contenttype.getbytes());
string contentlength = "content-length: " + datalength + "\r\n";
outstream.write(contentlength.getbytes());
string alive = "connection: keep-alive\r\n";
outstream.write(alive.getbytes());
string host = "host: " + url.gethost() + ":" + port + "\r\n";
outstream.write(host.getbytes());
// 写完http请求头后根据http协议再写一个回车换行
outstream.write("\r\n".getbytes());
// 把所有文本类型的实体数据发送出来
outstream.write(textentity.tostring().getbytes());
// 把所有文件类型的实体数据发送出来
stringbuilder fileentity = new stringbuilder();
fileentity.append("--");
fileentity.append(boundary);
fileentity.append("\r\n");
fileentity.append("content-disposition: form-data;name=\""
+ getparametername() + "\";filename=\"" + getfilname()
+ "\"\r\n");
fileentity.append("content-type: " + getcontenttype() + "\r\n\r\n");
outstream.write(fileentity.tostring().getbytes());
if (getinstream() != null) {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = getinstream().read(buffer, 0, 1024)) != -1) {
outstream.write(buffer, 0, len);
}
getinstream().close();
} else {
outstream.write(getdata(), 0, getdata().length);
}
outstream.write("\r\n".getbytes());
// 下面发送数据结束标志,表示数据已经结束
outstream.write(endline.getbytes());
bufferedreader reader = new bufferedreader(new inputstreamreader(socket.getinputstream()));
if (reader.readline().indexof("200") == -1) {// 读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outstream.flush();
outstream.close();
reader.close();
socket.close();
return true;
}
}
//测试代码
file iconfile = new file("file路径");
string url="htttp://192.168.1.101:8080/app/initservlet";
map<string, string> map = new hashmap<string, string>();//表单内容
map.put("name","blog");
if (iconfile != null) {
formfile uploadfile = new formfile(iconfile.getname(),
iconfile, "iconfile", "image/jpeg");
uploadfile.setoper("action=insertusr");//在url上插入?action=insertusr
try {
boolean isok = uploadfile.post(url, map);
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}