struts1.x文件上传

jsp表单页面(upload.jsp)


<!-- form表单必须是post提交,且要配置enctype="multipart/form-data" -->
   <form action="upload.do" method="post" enctype="multipart/form-data">
   		文件路径:<input type="file" name="file"><br>
   		<input type="submit" value="提交"><br>
   </form>
   ${msg }



ActionForm


import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;

public class UploadForm extends ActionForm {
	//注意类型
	private FormFile file;
	
	public FormFile getFile() {
		return file;
	}
	public void setFile(FormFile file) {
		this.file = file;
	}
}



Action


public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UploadForm uf = (UploadForm) form;
		FormFile ff = uf.getFile();
		System.out.println("源文件名:"+ff.getFileName());
		System.out.println("源文件大小:"+ff.getFileSize());
                  //写到磁盘
		FileOutputStream fout = new FileOutputStream(new File("d://"+ff.getFileName()));
		fout.write(ff.getFileData());
		fout.flush();
		fout.close();
                   //添加页面返回信息
		request.setAttribute("msg", "上传成功");
		return mapping.findForward("success");
	}



xml文件配置

<form-beans>
   <form-bean name="uploadForm" type="com.cao.form.UploadForm" />
</form-beans>
<action-mappings>
   <action path="/upload" 
					type="com.cao.action.UpLoadAction" 
					name="uploadForm" 
					scope="request">
				<forward name="success" path="/upload.jsp" />
			</action>
</action-mappings>

<!-- 此标签可以配置上传文件的大小 -->
	<controller maxFileSize="3M" />



你可能感兴趣的:(java,apache,jsp,xml,struts)