说明:struts中上传文件-FormFile应用,希望用最简单的表达使你马上知道怎么用。

Web开发网资料库
1:上传用的页面举例:uploadFile.jsp
<%@ page language=
"java"%>
<%@ taglib uri=
"/WEB-INF/struts-html.tld" prefix="html"%>

<html>
<head>
<title>JSP for uploadsActionForm form</title>
</head>
<body>
<html:form action=
"/uploadsAction" enctype="multipart/form-data"> <1>
theFile : <html:file property=
"files"/><br/>
<html:submit/><html:cancel/>
</html:form>
</body>
</html>
2:后台form的定义:UploadsActionForm.java
package struts.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class UploadsActionForm extends ActionForm {
protected FormFile files;
public FormFile getFiles() {
return files;
}
public void setFiles(FormFile file) {
this.files = file;
}
}
3:后台代码实现
:UploadsActionAction.java
package struts.action;
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 struts.form.UploadsActionForm;
import org.apache.struts.upload.FormFile;
import java.io.*;
public class UploadsActionAction extends Action {
public ActionForward execute(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response)
throws Exception {

String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase(
"utf-8")))
{
response.setContentType(
"text/html; charset=gb2312");//如果没有指定编码,编码格式为gb231
}
UploadsActionForm theForm = (UploadsActionForm ) form;
FormFile file = theForm.getFiles();
//取得上传的文
try {
InputStream stream = file.getInputStream();
//把文件读
String filePath = request.getRealPath(
"/upload");//上传到指定的upload包
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath +
"/" +
                               file.getFileName());
//建立一个上传文件的输出
//System.out.println(filePath+"/"+file.getFileName())
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
//将文件写入服务
}
bos.close();
stream.close();
}catch(Exception e){
System.err.print(e);
}
//request.setAttribute("dat",file.getFileName())
return mapping.findForward(
"display");
}
}