利用了struts1.2的jar包,如何添加jar包:如果用Eclipse可以在项目上右键直接从MyEclipse-->Add struts .
如图
然后开始编码,步骤如下:
1.页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="gb2312"%>
<html>
<body>
<form action="<%=request.getContextPath() %>/admin/HtmlFile.do" method="post" enctype="multipart/form-data" name="HtmlFileForm">
<input type="file" name="file" />
<html:submit />
</form>
</body>
</html>
2.写文件Form
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class HtmlFileForm extends ActionForm {
private static final long serialVersionUID = -8008580023746850586L;
public HtmlFileForm() {
}
private FormFile file;
public FormFile getFile() {
return this.file;
}
public void setFile(FormFile file) {
this.file = file;
}
private String fname;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
private String size;
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
3.写Action
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
public class HtmlFileAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String dir = servlet.getServletContext().getRealPath("/upload");
HtmlFileForm hff = (HtmlFileForm) form;
FormFile file = hff.getFile();
// if no file was uploaded,then display View
if (file == null) {
return mapping.findForward("fail");
}
// Get name and file size
String fname = file.getFileName();
String size = Integer.toString(file.getFileSize()) + "bytes";
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(dir + "/" + fname);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while((bytesRead = streamIn.read(buffer,0,8192))!=-1){
streamOut.write(buffer,0,bytesRead);
}
streamOut.close();
streamIn.close();
//
hff.setFname(fname);
//Clean up our toys when done playing
file.destroy();
//Forward to default display
request.setAttribute("inputfile", fname);
return mapping.findForward("success");
}
}
__________________________________________________________________
可以到这里下载源码:http://dl.javaeye.com/topics/download/db0c7116-3a8e-3a6d-9dde-2cc82e0c5f50
需要先注册账号。
http://yuanyuan7891.javaeye.com/blog/711312