标签:
1.图片上传 ENCTYPE="multipart/form-data"用于表单里有图片上传。
jsp:
<input type="file" name="image">
struts.xml
<action name="" class="" method=""> <!--动态设置savePath的属性 --> <param name="savePath">table_images</param> <interceptor-ref name="fileUpload"> <!-- 文件过滤 --> <param name="allowedTypes">image/bmp,image/png,image/gif,image/jpeg</param> <!-- 文件大小, 以字节为单位 --> <param name="maximumSize">1025956</param> </interceptor-ref> <!-- 默认拦截器必须放在fileUpload之后,否则无效 --> <interceptor-ref name="defaultStack" /> </action>
action:
// 封装上传文件域的属性 private File image; // 封装上传文件类型的属性 private String imageContentType; // 封装上传文件名的属性 private String imageFileName; // 接受依赖注入的属性 private String savePath; public File getImage() { return image; } public void setImage(File image) { this.image = image; } public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public String getImageFileName() { return imageFileName; } public void setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; }
具体操作方法:
FileOutputStream fos = null; FileInputStream fis = null; try{ ActionContext ac = ActionContext.getContext(); ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT); System.out.println(sc.getRealPath("/") + getSavePath() + "\\" + getImageFileName()); fos = new FileOutputStream(sc.getRealPath("/") + getSavePath() + "\\" + getImageFileName()); // 建立文件上传流 fis = new FileInputStream(getImage()); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } catch (Exception e) { System.out.println("文件上传失败"); e.printStackTrace(); } finally { close(fos, fis); }
最后不要忘记关掉输入输出流
标签:
原文地址:http://www.cnblogs.com/xy-1988xcl/p/5284056.html