Struts中上传文件
由于心情+事情的原因,在做文件上传的Demo时,我没有具体的实现,虽然看了两次视频,但是现在做起来感觉到还是有一些问题,果然是好记性不如烂笔头。今天就着已经实现了的机会,写一下注意事项。
?
在JSP页面中,我们的表单如下:
?
<form action="fileupload.do" enctype="multipart/form-data"method="post">文件名称:<input type="text" name="title" /><br />文件路径:<input type="file" name="myfile" /><br /><input type="submit" value="提交" /></form>
?
?
form表单中有三个属性,其中action是与struts-config.xml中的path路径相对应的,enctype属性必须是上面的这种格式,这样才允许文件上传上去。同样的method方法也必须标明为post,否则的话会出现如下所示的错误:
?
root cause java.lang.IllegalArgumentException: Cannot invoke com.cx.struts.FileActionForm.setMyfile - argument type mismatchorg.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:1778)org.apache.commons.beanutils.PropertyUtilsBean.setSimpleProperty(PropertyUtilsBean.java:1759)org.apache.commons.beanutils.PropertyUtilsBean.setNestedProperty(PropertyUtilsBean.java:1648)org.apache.commons.beanutils.PropertyUtilsBean.setProperty(PropertyUtilsBean.java:1677)org.apache.commons.beanutils.BeanUtilsBean.setProperty(BeanUtilsBean.java:1022)org.apache.commons.beanutils.BeanUtilsBean.populate(BeanUtilsBean.java:811)org.apache.commons.beanutils.BeanUtils.populate(BeanUtils.java:298)org.apache.struts.util.RequestUtils.populate(RequestUtils.java:493)org.apache.struts.action.RequestProcessor.processPopulate(RequestProcessor.java:816)org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:203)org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)javax.servlet.http.HttpServlet.service(HttpServlet.java:627)javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
?
?
顺便看一下我们的Action实现吧:
public class UploadAction extends Action {@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {FileActionForm faf=(FileActionForm)form;String title=faf.getTitle();String fileName=faf.getMyfile().getFileName();FileOutputStream fos=new FileOutputStream("C:\"+fileName);fos.write(faf.getMyfile().getFileData());fos.flush();fos.close();System.out.println(title);System.out.println(fileName);return mapping.findForward("success");}}
?