Java以struts2为例介绍如何实现图片上传

这篇文章主要介绍了Java struts2中如何实现图片上传的相关资料,需要的朋友可以参考下

总的说图片上传有两种方式,一种是把图片文件写到数据库中,另一种是存到服务器文件目录中。写到数据库中的图片文件需要转换成二进制流的格式,占用数据库空间比较,适合少量图片的存储,比如说,系统中某些小图标,写到数据库中的优点是比较安全,不容易被用户不小心删除

在struts2中实现(以图片上传为例)

1.FileUpload.jsp代码清单如下:

The FileUplaodDemo In Struts2

2.ShowUpload.jsp的功能清单如下:

ShowUpload "/>

3.FileUploadAction.java的代码清单如下 :

package com.chris; import java.io.*; import java.util.Date; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class FileUploadAction extends ActionSupport{ private static final long serialVersionUID = 572146812454l ; private static final int BUFFER_SIZE = 16 * 1024 ; //注意,文件上传时同时与myFile,myFileContentType,myFileFileName绑定 //所以同时要提供myFileContentType,myFileFileName的set方法 private File myFile; //上传文件 private String contentType;//上传文件类型 private String fileName; //上传文件名 private String imageFileName; private String caption;//文件说明,与页面属性绑定 public void setMyFileContentType(String contentType) { System.out.println("文件类型 : " + contentType); this .contentType = contentType; } public void setMyFileFileName(String fileName) { System.out.println("文件名称 : " + fileName); this .fileName = fileName; } public void setMyFile(File myFile) { this .myFile = myFile; } public String getimageFileName() { return imageFileName; } public String getCaption() { return caption; } public void setCaption(String caption) { this .caption = caption; } private static void copy(File src, File dst) { try { InputStream in = null ; OutputStream out = null ; try { in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE); out = new bufferedoutputstream( new FileOutputStream(dst), BUFFER_SIZE); byte [] buffer = new byte [BUFFER_SIZE]; while (in.read(buffer) > 0 ) { out.write(buffer); } } finally { if ( null != in) { in.close(); } if ( null != out) { out.close(); } } } catch (Exception e) { e.printstacktrace(); } } private static String getExtention(String fileName) { int pos = fileName.lastIndexOf("."); return fileName.substring(pos); } @Override public String execute() { imageFileName = new Date().getTime() + getExtention(fileName); File imageFile = new File(ServletActionContext.getServletContext().getRealPath("UploadImages" ) + "/" + imageFileName); copy(myFile, imageFile); return SUCCESS; } }

注:此时仅为方便实现Action所以继承ActionSupport,并Overrider execute()方法

在struts2中任何一个POJO都可以作为Action

4.struts.xml清单如下:

/ShowUpload.jsp

5.web.xml清单如下:

struts-cleanup org.apache.struts2.dispatcher.ActionContextCleanUp struts-cleanup /* struts2org.apache.struts2.dispatcher.Filterdispatcherstruts2/*Index.jsp

以上内容是小编给大家介绍的Java struts2中如何实现图片上传的全部内容,希望大家喜欢。

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...