首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

利用File类进行文件下传

2012-10-29 
利用File类进行文件上传第一步:在jsp页面中,注意负责上传文件的控件要使用html:file标签,在html:form处注

利用File类进行文件上传
第一步:
在jsp页面中,注意负责上传文件的控件要使用html:file标签,在html:form处注意加上enctype=“multipart/form-data”  method为post
1、
<html:formmethod="post"action="/save_user"enctype="multipart/form-data" >
2、
<tr>
           <td>头像:</td>
           <td><html:file property="image" /></td>
</tr>

第二步:
在对应的表单form中定义private FormFile image属性,当然自动生成set和get方法。

第三步:
在pojo中声明一个属性与上传控件对应。

第四步:
在相应的Action中的方法里加入上传的代码:
例如:

UserForm userForm = (UserForm) form;UserDAO dao = new UserDAO();String message = null;String basePath = this.getServlet().getServletContext().getRealPath("/");//获取项目根路径try {dao.getSession().beginTransaction();User temp = (User) dao.findByUserName(userForm.getUserName());if (temp == null) {User user = new User();userForm.fillToUserBean(user);if (userForm.getImage().getFileName().length() > 0) {//判断是否有选择上传文件,如果有则文件长度>0String path = "/uploadImages/" + //这里的"/uploadImages/"指的是什么?它是我们自行在WebRoot下面创建的用于存放上传文件的文件夹的名称,即:如果我们将上传的文件存放在uploadfile中,我们要做的是在WebRoot下新建一个名为uploadfile的文件夹,并且这里的代码要改为:"/uploadfile/"dao.picturePath(userForm.getImage());//这里我们用到了一个自己在DAO中写的名为picturePath的方法,其目的是为了将上传的文件跟换一个不会和数据库已有数据重复的文件名称,这样的好处是即使上传的多个文件实质上一个,但有需要将其区分开时比较方便。再介绍完Action的写法之后我们再来讲解DAO中方法的写法。String endstring = userForm.getImage().getFileName().substring(userForm.getImage().getFileName().lastIndexOf(".") + 1);if ("jpg".equals(endstring) || "png".equals(endstring)|| "gif".equals(endstring)) {try {dao.saveFile(userForm.getImage(), basePath, path);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}user.setHeaderImg(path);} else {user.setHeaderImg("");}}dao.save(user);dao.getSession().getTransaction().commit();return mapping.findForward("index");


第五步
在DAO中我们需要修改saveFile,添加picturePath方法,具体代码如下:
saveFile
public void saveFile(FormFile formfile, String basePath, String path)throws IOException {FileOutputStream fos = null;BufferedInputStream in = null;BufferedOutputStream out = null;try {fos = new FileOutputStream(basePath + path);in = new BufferedInputStream(formfile.getInputStream());out = new BufferedOutputStream(fos);byte[] buf = new byte[8192];int readsize;while ((readsize = in.read(buf)) != -1) {out.write(buf, 0, readsize);out.flush();}} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {if (fos != null)try {fos.close();} catch (Exception err) {err.printStackTrace();}if (in != null)try {in.close();} catch (Exception err) {err.printStackTrace();}if (out != null)try {out.close();} catch (Exception err) {err.printStackTrace();}}}picturePathpublic String picturePath(FormFile formfile) {String filename = "";UUIDGenerator g = new UUIDGenerator();// UUIDGenerator是我们自行编写的一个自动生成名字的一个类,之后会给出具体代码。filename = formfile.getFileName();if (filename.length() > 0) {filename = filename.substring(filename.lastIndexOf("."));}filename = (String) g.generate() + filename;return filename;}





第六步:
编写工具类:UUIDGenerator
import java.io.Serializable;import java.net.InetAddress;public class UUIDGenerator { private static final int IP; public static int IptoInt( byte[] bytes ) {  int result = 0;  for (int i=0; i<4; i++) {   result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];  }  return result; } static {  int ipadd;  try {   ipadd = IptoInt( InetAddress.getLocalHost().getAddress() );  }  catch (Exception e) {   ipadd = 0;  }  IP = ipadd; } private static short counter = (short) 0; private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 ); public UUIDGenerator() { } protected int getJVM() {  return JVM; } protected short getCount() {  synchronized(UUIDGenerator.class) {   if (counter<0) counter=0;   return counter++;  } } protected int getIP() {  return IP; } protected short getHiTime() {  return (short) ( System.currentTimeMillis() >>> 32 ); } protected int getLoTime() {  return (int) System.currentTimeMillis(); }  private final static String sep = ""; protected String format(int intval) {  String formatted = Integer.toHexString(intval);  StringBuffer buf = new StringBuffer("00000000");  buf.replace( 8-formatted.length(), 8, formatted );  return buf.toString(); } protected String format(short shortval) {  String formatted = Integer.toHexString(shortval);  StringBuffer buf = new StringBuffer("0000");  buf.replace( 4-formatted.length(), 4, formatted );  return buf.toString(); } public Serializable generate() {  return new StringBuffer(36)   .append( format( getIP() ) ).append(sep)   .append( format( getJVM() ) ).append(sep)   .append( format( getHiTime() ) ).append(sep)   .append( format( getLoTime() ) ).append(sep)   .append( format( getCount() ) )   .toString(); }}

热点排行