Struts1文件上传

摘要

前台jsp页面代码,处理struts1文件上传过程,具体请看下面代码。

   1.前台jsp页面代码

<%@page pageEncoding = "UTF-8"%>
<h1>
    文件上传例子
</h1>
<hr />
<form action="upload.action" method="post" enctype="multipart/form-data">
    名称:
    <input type="text" name="name" />
    <br />
    开始上传:
    <input type="file" name="file" />
    <br />
    <input type="submit" value="上传" />
</form>

2.UploadForm代码

package fileUpload.singleFileUpload.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class UploadForm extends ActionForm {
    private static final long serialVersionUID = 1L;
    private String name;
                                                                                                                                                                                                                                  
    private FormFile file;
                                                                                                                                                                                                                               
        private String fileSize;      
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public FormFile getFile() {
        return file;
    }
    public void setFile(FormFile file) {
        this.file = file;
    }
}

FormFile是Struts1专门用来处理文件上传和下载的,注意属性name,file名字必须与jsp页面一致,否则会报空指针。

3.UploadAction中的代码

package fileUpload.singleFileUpload.action;
import java.io.FileOutputStream;
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;
import fileUpload.singleFileUpload.form.UploadForm;
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
   UploadForm uf = (UploadForm)form;
   String name = uf.getName();
   FormFile file = uf.getFile();
   System.out.println("name=" + name);
   String filename = file.getFileName();
   System.out.println("fileName=" + filename);
                    
   FileOutputStream fos = new FileOutputStream("d:\\["+name+"]" + filename); //创建输出流
   fos.write(file.getFileData()); //写入
   fos.flush();//释放
   fos.close(); //关闭
   return mapping.findForward("success");
 }
}

4.Struts配置文件

<form-bean name="uploadForm" type="fileUpload.singleFileUpload.form.UploadForm" />


IT家园
IT家园

网友最新评论 (0)