JAVA------Sturts图片上传

xiaoxiao2026-03-14  14

[align=left][/align][size=medium][/size][color=green]JAVA------Sturts图片上传 第一步:建立一个图片FileUpload 类:{其他的什么导入Sturts框架我就在这里不写啦} 代码演示如下{----} public class FileUpload { public void upload(String path,InputStream is){ try { OutputStream os = new FileOutputStream(path); byte[] buffer = new byte[1028*8]; int len; try { while((len=is.read(buffer))!=-1){ os.write(buffer, 0, len); } os.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } } ********************************************************************************************** 第二步:创建一个实体类 private int u_id; private String u_name; private String u_pass; private String picture; 然后把上面几个属性get/set *********************************************************************************************** 第三步:创建一个Action public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { DynaActionForm userForm = (DynaActionForm) form;// TODO Auto-generated method stub User user = (User) userForm.get("user"); String fileName = this.upload(userForm); user.setPicture(fileName); if(!ubiz.addUser(user)){ return mapping.findForward("error"); } return this.list(mapping, userForm, request, response); <!-- 功能说明: 调用FileUpload方法--> public String upload(DynaActionForm userForm){ FileUpload up = new FileUpload(); FormFile formFile = (FormFile) userForm.get("formFile"); String fileName = formFile.getFileName(); String path = servlet.getServletContext().getRealPath("/")+"upload/"+fileName; InputStream is = null; try { is = formFile.getInputStream(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } up.upload(path, is); formFile.destroy(); return fileName; } *********************************************************************************************** 第四步:配置Sturts{特别要注意} <form-beans > <form-bean name="userForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="user" type="org.svse.entity.User"></form-property> <form-property name="hidden" type="java.lang.String"></form-property> <form-property name="formFile" type="org.apache.struts.upload.FormFile"></form-property> </form-bean> 第五步:使用Html标签 <html:file property="formFile"></html:file> [/color] 相关资源:struts2图片单张和多张上传功能
转载请注明原文地址: https://www.6miu.com/read-5045870.html

最新回复(0)