struts文件上传

xiaoxiao2026-09-14  18

[align=center]Struts文件上传[/align] 1. 页面配置: <form action="upload.do" method="post" enctype="multipart/form-data"> 标题:<input type="text" name="title"><br> 文件:<input type="file" name="file"><br> <input type="submit" value="提交"> </form> 2. ActionForm中使用FormFile来接受上传文件,代码如下: public class UploadForm extends ActionForm { private FormFile file; public FormFile getFile() { return file; } public void setFile(FormFile file) { this.file = file; }} 3. 在Action中使用FormFile来接收上传文件,代码如下: public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { ActionForward af = null; UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub FormFile myFile = uploadForm.getFile(); if(myFile!=null){ try { FileOutputStream fos = new FileOutputStream("c:\\"+myFile.getFileName()); fos.write(myFile.getFileData()); fos.flush(); fos.close(); af = mapping.findForward("success"); } catch (Exception e) { e.printStackTrace(); af = mapping.findForward("error"); } } return af; } 4. 在struts-config.xml中的配置 <action attribute="uploadForm" name="uploadForm" path="/upload" scope="request" type="com.zsw.struts.action.UploadAction" > <forward name="success" path="/upload_success.jsp" /> <forward name="error" path="/upload_error.jsp" /></action> ---------------------------------------------------------------- 补充: 文件下载 //下载公文附件 public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DocumentActionForm daf = (DocumentActionForm)form; Document document = documentManager.findDocument(daf.getId()); response.reset(); response.setContentType("application/x-download;charset=GBK"); response.setHeader("Content-Disposition", "attachment;filename=temp.doc"); response.getOutputStream().write(document.getContent()); response.getOutputStream().flush(); response.getOutputStream().close(); //指示struts,不要对返回值进行处理 return null; }
转载请注明原文地址: https://www.6miu.com/read-5052679.html

最新回复(0)