java-文件上传案例

来源:互联网 发布:vmware fusion mac 编辑:程序博客网 时间:2024/05/16 09:58

java-文件上传案例
首先,4个jar驱动包下载地址:http://www.jsharer.com/file/809237.htm
只个包保证能够顺利执行一下案例 的前提,请大家务必下载使用!

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
在此发布下我的QQ群号,望一起讨论
37424970 开源

涉及所有关于java方面的编程均可讨论   本人目前涉及MYSQL ORACLE LINUX AJAX SSH XML.......

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>..

JSP页面代码:4.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP '4.jsp' starting page</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/#">
 
 function aa()
 {
  var aa=document.all.filename.value;
 // window.alert(aa);
  document.all.dd.action="UploadFile?filename="+document.all.filename.value;
  //window.open("UploadFile?filename="+document.all.filename.value,"_self");
 }
 function bb()
 {
  //window.alert(document.all.dd.action);
 }
 
  </script>

  </head>
 
  <body>
   
 <form action="UploadFile" id="dd" enctype="multipart/form-#" method="post">
  附件:<input type="file" name="filename" value="附件" onchange="aa();"/>&nbsp;
 <input type="submit"  value="提交" onclick="bb();" />
 </form>

  </body>
</html>

******************************************************************************************************************
部分解释:document.all.dd.action="UploadFile?filename="+document.all.filename.value;
这句话就是把<form action="UploadFile" id="dd" enctype="multipart/form-#" method="post">这里的form的action的值换成带参数的文件名传到后台处理。还要记住:这里有句话必不可少: enctype="multipart/form-#" 不然会出现莫名其妙的的错误的。这样说,是为了大家以后遇到麻烦 摸不着北·
******************************************************************************************************************

servlet文件:名为:UploadFile.java

package com.yeeyoo.message;//这是我文件所在的包

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

 

import org.apache.commons.fileupload.*;
import org.apache.commons.*;

import com.yeeyoo.Bo.UsersBo;
import com.yeeyoo.message.*;
import com.yeeyoo.model.Users;

public class UploadFile extends HttpServlet {
 
 
 private static final String CONTENT_TYPE="text/html;charest=GBK";
 //实例化对象 
 HttpServletRequest request;
 HttpServletResponse response;
 
 HttpSession hs;
 Users u;
 public void init() throws ServletException
 {
  
 }
 

 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  String geter = "";
  String title = "";
  String content = "";

  String md5 = "";

  this.request = request;
  this.response = response;

  response.setContentType(CONTENT_TYPE);
  hs = request.getSession(true);
  u = (Users) hs.getAttribute("myinfo");

  //System.out.println("realPath===========" + request.getRealPath("/"));
  //request.getRealPath("/")   --表示取得当前服务器的tomcat下的webhaps所在目录

  DiskFileUpload dfu = new DiskFileUpload();
  // 设置允许上传文件的大小
  dfu.setSizeMax(100 * 1024 * 1024);

  // 设置在内存中存储数据的大小
  dfu.setSizeThreshold(4096);

  // 如果文件超过 Threshold 的值,就将它存放的 当前服务器的tomcat下的webhaps所在目录/users/该用户的所在空间的文件名/temp/upload/ 文件夹里
  dfu.setRepositoryPath(request.getRealPath("/") + "users/"+request.getSession().getAttribute("u_name")+"/image/temp/");

  // 开始读取上传信息
  List fileList = null;
  try {
   fileList = dfu.parseRequest(this.request);
  } catch (FileUploadException ex) {
   System.out.println("转换 request 异常!");
   ex.printStackTrace();
  }

  // 迭代器
  // java.util.Iterator it=fileList.iterator();
  Iterator it = fileList.iterator();
  System.out.println("11");

  while (it.hasNext()) {
   System.out.println("22");
   FileItem fi = (FileItem) it.next();
   // 说明是文件
   String filename = fi.getName().substring(
     fi.getName().lastIndexOf("//") + 1);//取得上传的文件名
   
   System.out.println("filename11111111111======" + filename);

   String lastfilename = filename
     .substring(filename.lastIndexOf(".") + 1);//取得上传文件名的后缀
   System.out.println("lastfilename============"+lastfilename);
   if (lastfilename.equals("jpg") || lastfilename.equals("gif")
     || lastfilename.equals("jpeg") || lastfilename.equals("JPG")
     || lastfilename.equals("GIF") || lastfilename.equals("JPEG")
     || lastfilename.equals("PNG") || lastfilename.equals("png")) //解决后缀问题,这里是指图片格式,也可换成别的格式,从数据库中得出也可以
   {
    //说明该文件符合上传条件
    System.out.println("lastfilename1============"+lastfilename);
    //request.setAttribute("wenjianerr", "false");
    //response.sendRedirect("/yeeyoo/jsp/users/right_index2_top.jsp");
   //} else {

   // System.out.println("lastfilename2============"+lastfilename);
    md5 = RandomGUID.newGuid();//生成MD5值,至于怎么生成,请查看我原来发布的代码文件:
      //生成唯一32位ID编码代码,以满足对ID编号的唯一性加资源性解决问题:地址:http://hi.baidu.com/zhuseahui/blog/item/35747fa99797f9fa1e17a28d.html
    long size = fi.getSize();//读取文件长度,在此也可限制文件长度
    System.out.println("size===========" + size);
    try {//开始上传
     if (filename != null && !filename.equals(" ")) {
      // System.out.println("filename222222222222==========="+filename);
      fi.write(new File(request.getRealPath("/")
        + "users/"+request.getSession().getAttribute("u_name")+"/image/upload/" + md5+"."+lastfilename));//这里的md5+"."+lastfilename是指把这个MD5生成的值加上刚才的文件后缀,取得新的文件名,放入文件夹中
     }
     System.out.println("上传成功");
    } catch (Exception e) {
     // TODO: handle exception

     e.printStackTrace();

     System.out.println("上传失败");
    }
    

    int uid = Integer.parseInt((String) request.getSession()
      .getAttribute("u_id"));

    UsersBo ub = new UsersBo();
    ub.updateUsersU_image(md5+"."+lastfilename, uid);//添加数据库操作,.就是把生成的文件名添加到数据库中
    request.getSession().setAttribute("wenjianerr", "true");//想缓存中放入wenjianerr的值,若不为true,那表示改文件未上传成功或格式不正确
    //response.sendRedirect("/yeeyoo/jsp/users");
   }
   else
   {
    System.out.println("lastfilename2============"+lastfilename);
    request.getSession().setAttribute("wenjianerr", "false");
    
  

   
   }
  }
  response.sendRedirect("/yeeyoo/jsp/users/ziliao");//实现页面跳转,不会一直就在次不动吧,呵呵


  
 }

 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to
  * post.
  *
  * @param request
  *            the request send by the client to the server
  * @param response
  *            the response send by the server to the client
  * @throws ServletException
  *             if an error occurred
  * @throws IOException
  *             if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

  this.doGet(request, response);//合二为一,就是把post的方法和get方法传为一个方法
 }

}

////////////////////////////////////////////////////////////////////////////////////////
javabean代码:
Users.java类代码,这是添加数据库方面的,可以忽略不看 

package com.yeeyoo.model;

import java.util.Date;


/**
 * Users generated by MyEclipse - Hibernate Tools
 */

public class Users  implements java.io.Serializable {


    // Fields   

     private Integer UId;
 ......
     private String UImage;
.....


    // Constructors

    /** default constructor */
    public Users() {
    }

 /** minimal constructor */
    public Users(.........) {
    ...........
    }
   
    /** full constructor */
    public Users(....., String UImage,......) {
.....
        this.UImage = UImage;
.....
    }

  
    // Property accessors

    public Integer getUId() {
        return this.UId;
    }
   
    public void setUId(Integer UId) {
        this.UId = UId;
    }

......

    public String getUImage() {
        return this.UImage;
    }
   
    public void setUImage(String UImage) {
        this.UImage = UImage;
    }

.......
  
}

UsersBo.java类文件,这是那个执行BO的文件,是操作数据库的,可以忽略
package com.yeeyoo.Bo;

import java.util.ArrayList;
import java.util.Date;

import com.yeeyoo.model.Users;

public class UsersBo {

 MyTools mt=new MyTools();
 String hql="";
 public boolean updateUsersU_image(String md5, int uid) {
  // TODO 自动生成方法存根
  hql="update Users set u_image='"+md5+"' where u_id='"+uid+"'";
  return mt.update_all(hql);
 }
 
}

/////////////////////////////////////////////////////////////////////////////////////////////

web.xml文件配置:
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>UploadFile</servlet-name>
    <servlet-class>com.yeeyoo.message.UploadFile</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadFile</servlet-name>
    <url-pattern>/UploadFile</url-pattern>
  </servlet-mapping>

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

好了,记住:把那先下的那4个jar包复制到项目的lib文件下,或jdk的ext下.,怎么样?尝试下吧???
有问题:邮箱讨论@!
本人邮箱:zhuseahui@yahoo.com.cn

原创粉丝点击