html文件上传:
html部分界面:
<form action="http://localhost:8080/hub/container/addContainer" method="post" enctype="multipart/form-data">
war包:<input type="file" name="attach" id="attach" size="50" >
<input type="submit" value="提交">
</form>
/**
* 接收从客户端上传的文件,并保存在本地
*/
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
。。。
private String uploadFile() {
String newFileName="";
try {
String MsgFilesURL_PATH = "";
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;
// 获得未见过滤器
File file = wrapper.getFiles("attach")[0];
// 获得上传的文件名
String fileName = wrapper.getFileNames("attach")[0];
// ----------重新构建上传文件名---------
final Lock lock = new ReentrantLock();
String newName = null;
lock.lock();
try {
// 加锁为防止文件名重复
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyyMMddHHmmss");
newName = formatter.format(new Date()) + fileName;
} finally {
lock.unlock();
}
// ------锁结束---------
// 获取文件输出流
newFileName=request.getSession().getServletContext().getRealPath("/")
+ MsgFilesURL_PATH + newName;
FileOutputStream fos = new FileOutputStream(newFileName);
// 获取内存中当前文件输入流
InputStream in = new FileInputStream(file);
try {
int len = in.available();
byte[] buffer = new byte[len];
in.read(buffer);
fos.write(buffer);
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
in.close();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return newFileName;
}
//模拟浏览器提交表单数据,上传文件
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
。。。
private int postFile(String URLString, String filePath,String json) {
File targetFile = new File(filePath);
PostMethod filePost = new PostMethod(URLString);
try
{
//通过以下方法可以模拟页面参数提交
Part[] parts = {new StringPart("json", json), new FilePart("attach", targetFile) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK){
return 0;//上传成功
}else{
return -1;//上传失败
}
}
catch (Exception ex){
return -1;
}
finally{
filePost.releaseConnection();
}
}