struts1.x 文件上传
前端jsp代码 upLoad.jsp
<%@ page pageEncoding="GBK"%> <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <html> <head> <title>上传单个文件(文件大小不能超过2M) </title> </head> <body> <%-- 在<html:form>标签中必须加enctype="multipart/form-data" --%> <html:form enctype="multipart/form-data" action="uploadfile"> <html:file property="myFile"/><p> <%-- 使用<html:file>标签让用户输入上传文件名 --%> <html:submit value="上传"/> </html:form> </body> </html>
Action端代码 UpLoadAction.java
package com.mocha.xxx.action; import javax.servlet.http.*; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; import com.mocha.xxx.form.UploadForm; import java.io.*; public class UploadAction extends Action { protected void saveFile(FormFile formFile,String path) throws Exception { InputStream in = formFile.getInputStream(); // 获得上传文件的InputStream // 在服务端指定的上传路径中建立一个空的文件(文件名为getFileName()方法返回的值) String temString= path+"\\image\\" + formFile.getFileName(); System.out.println(temString); FileOutputStream fout = new FileOutputStream(path+"\\image\\" + formFile.getFileName()); byte buffer[] = new byte[8192]; int count = 0; // 开始向上传路径中刚建立的文件写入数据,每次写8k字节 while ((count = in.read(buffer)) > 0) { fout.write(buffer, 0, count); } fout.close(); formFile.destroy(); // 上传成功后,销毁当前上传文件的资源 } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { UploadForm uForm = (UploadForm) form; PrintWriter out = null; try { // String path= this.getServlet().getServletContext().getRealPath("/"); String path = request.getRealPath("/"); //System.out.println(path); response.setCharacterEncoding("GBK"); out = response.getWriter(); saveFile(uForm.getMyFile(),path); // 将上传文件保存到指写的路径(在web.xml中配置) out.println("上传文件成功."); } catch (Exception e) { e.printStackTrace(); } return null; } }
ActionForm UploadForm.java
package com.mocha.xxx.form; import org.apache.struts.action.*; import org.apache.struts.upload.FormFile; public class UploadForm extends ActionForm { private FormFile myFile; // 这个myFile代表要上传的文件 public FormFile getMyFile() { return myFile; } public void setMyFile(FormFile myFile) { this.myFile = myFile; } }
struts配置文件
<form-beans> <form-bean name="uploadForm" type="com.mocha.xxx.form.UploadForm"></form-bean> </form-beans>
<action name="uploadForm" parameter="method" scope="request" path="/uploadfile" type="org.springframework.web.struts.DelegatingActionProxy"> <forward name="index" path="/index.jsp"></forward> <forward name="success" path="/index.jsp"></forward> </action>
相关推荐
lupeng 2020-11-14
sjcheck 2020-11-10
sjcheck 2020-11-03
meylovezn 2020-08-28
owhile 2020-08-18
Francismingren 2020-08-17
pythonclass 2020-07-29
sunzhihaofuture 2020-07-19
爱读书的旅行者 2020-07-07
行吟阁 2020-07-05
tianqi 2020-07-05
行吟阁 2020-07-04
冰蝶 2020-07-04
lyg0 2020-07-04
owhile 2020-07-04
opspider 2020-06-28
lengyu0 2020-06-28
tianqi 2020-06-21
dadaooxx 2020-06-16