if(files!=null)
for(FormBean file : files){
//filename为在服务端接收时希望保存成的文件名,filepath是本地文件路径(包括了源文件名),filebean中就包含了这俩属性
formParams.add(new FilePart("file", file.getFilename(), new File(file.getFilepath())));
}
Part[] parts = new Part[formParams.size()];
Iterator
int i=0;
while(pit.hasNext()){
parts[i++] = pit.next();
}
//如果出现乱码可以尝试一下方式
//StringPart sp = new StringPart("TEXT", "testValue", "GB2312");
//FilePart fp = new FilePart("file", "test.txt", new File("./temp/test.txt"), null, "GB2312"
//postMethod.getParams().setContentCharset("GB2312");
MultipartRequestEntity mrp = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(mrp);
//execute post method
HttpClient client = new HttpClient();
int code = client.executeMethod(post);
System.out.println(code);
} catch ...
}
通过以上代码可以成功的模拟java客户端发送post请求,服务端也能接收并保存文件
java端测试的main方法:
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
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)
for (Map.Entry
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; 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();
if (res == 200) {
InputStream in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return in.toString();
}
**********************
button响应中的代码:
**********************
***************************
服务器端servlet代码:
***************************
//print request.getInputStream to check request content
//HttpTool.printStreamContent(request.getInputStream());
RequestContext req = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(req)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setFileSizeMax(FILE_MAX_SIZE);
List items = new ArrayList();
try {
items = fileUpload.parseRequest(request);
} catch ...
Iterator it = items.iterator();
while(it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+new String(fileItem.getString().getBytes("ISO-8859-1"),"GBK"));
} else {
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+
fileItem.isInMemory()+" "+fileItem.getContentType()+" "+fileItem.getSize());
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
File newFile = new File(FILE_SAVE_PATH+fullFile.getName());
try {
fileItem.write(newFile);
} catch ...
} else {
System.out.println("no file choosen or empty file");
}
}
}
}
}
public void init() throws ServletException {
//读取在web.xml中配置的init-param
FILE_MAX_SIZE = Long.parseLong(this.getInitParameter("file_max_size"));//上传文件大小限制
FILE_SAVE_PATH = this.getInitParameter("file_save_path");//文件保存位置
}