struts文件上传

来源:互联网 发布:linux 防止ip地址欺骗 编辑:程序博客网 时间:2024/05/21 02:53

struts文件上传

文件上传按照我的理解就是从本地上选择某一文件上传到web容器指定的某一位置,而使用struts可以方便的实现这一功能。
文件上传需要这几个包:commons-io-1.1.jar commons-fileupload-1.1.1.jar,别的struts开头的就不说了.下面是实现案例。

Form类

import org.apache.struts.action.ActionForm;import org.apache.struts.upload.FormFile;public class FileUploadForm extends ActionForm {private FormFile file;public FormFile getFile() {return file;}public void setFile(FormFile file) {this.file = file;}}

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;public class FileUploadAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception {// TODO Auto-generated method stubSystem.out.println("执行FileAction中的execute方法");FileUploadForm fileForm = (FileUploadForm)form;FormFile file = fileForm.getFile();System.out.println("contentType:" + file.getContentType());System.out.println("fileName:" + file.getFileName());System.out.println("fileSize:" + file.getFileSize());//UPLOAD这一文件在WebRoot目录下String path = this.servlet.getServletContext().getRealPath("/UPLOAD");System.out.println("文件保存到:" + path);//File.separator//System.out.println("File.separator:" + File.separator);FileOutputStream fos = new FileOutputStream(path + file.getFileName());fos.write(file.getFileData());fos.close();return super.execute(mapping, form, request, response);}}
JSP页面
<html>  <head>    <title>FileUpload TEST</title>  </head>    <body style="margin: 2% 10%;">    <h2>File</h2>    <hr noshade="noshade">    <html:form action="FileUploadAction.do" method="POST" enctype="multipart/form-data">    <table border="1" style="border-collapse:separate;">    <tr>    <td>选择文件<td><html:file property="file"></html:file><tr>    <td><td><html:submit value="上传"></html:submit>    </table>    </html:form>  </body></html>
页面效果
点击上传,即可
最后Consoal弹出信息如下
Request原编码为:nullFilter设置Encoding为:UTF-8执行FileAction中的execute方法contentType:image/jpegfileName:001.jpgfileSize:405506文件保存到:D:\JAVA\Tomcat\apache-tomcat-8.0.21\webapps\Struts-Unti-1.3.10\UPLOAD\
因为文件名可能出现中文,所以要设置过滤器,(请看struts表单乱码解决方法)



0 0
原创粉丝点击