java学习

java学习

 

java文件上传下载

JAVA的文件上传遍一直是一个比较关注的问题,而且有几个NB东西提供了这个功能.

用的最多的算是三个(我就知道这三个)比较强的,一个是比较早的jspsmartupload,另一个是出身名族的commonupload,还有一个就是orellay的了.

我用的比较多是前两个,总的感觉是jspsmartuplod比较灵活,功能上更强一些(一点点吧),但是现在网上也不维护,也不能下载了,特别是 它上传的时候把上传文件放到内存里,所以上传文件的大小会和内存有关系.commonupload虽然没有提供很多API,但是它有比较灵活,它上传的过 程中会把上传的文件先写入磁盘,所以上传的大小只是带宽有关系,我尝试最大的上传文件的大小是700M,当然是本地测试:>

还有是就是在Linux/Unix系统上传文件的中文问题,我在下面的代码有了一些解决.

下面是前两种方式的上传代码:

try{
//取session 用户oid
int pid = userInfo.getUserId();
String sys_user_id = String.valueOf(pid);
//取init配置文件的参数值
String sitePhysicalPath = (String)init.getObject("SitePhysicalPath");
String saveDir = (String)init.getObject("InfoUploadDir");
String tempDir = (String)init.getObject("InfoUploadDir");
String fileMemo = ""; //文件说明
String fileName = null; //存储到数据库的文件名
String saveName = null; //存储到本地的文件名
String filePath = null; //存储到数据库的文件路径
String savePath = null; //存储到本地的文件路径
long fileSize = 0; //文件大小
int maxPostSize = -1;
int dinfo_upload_id = -1;
%>
<%
//初始化
mySmartUpload.initialize(pageContext);
//上载文件
mySmartUpload.upload();
//循环取得所有上载文件
for(int i=0; i<mySmartUpload.getFiles().getCount(); i++)
{
//取得上载文件
com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i);
if(!file.isMissing())
{
fileName = file.getFileName();
//取得文件扩展名file.getFileExt()
try{
saveName = fileName.substring(fileName.lastIndexOf("."));

}catch(Exception e){
saveName = "";
}
//取得文件大小
fileSize = file.getSize();
//存储路径
String sql_id = " SELECT S_INFO_UPLOAD.nextval as seqid FROM dual ";
try{
Statement stmt = con.createStatement();
ResultSet rst = stmt.executeQuery(sql_id);
while(rst.next())
{
dinfo_upload_id = rst.getInt("seqid");
}
}catch(SQLException sqle){
return;
}

filePath = sitePhysicalPath + saveDir + Integer.toString(dinfo_upload_id) + saveName;
savePath = saveDir + Integer.toString(dinfo_upload_id) + saveName;
//存储文件到本地
file.saveAs(filePath);
//存储文件到数据库
switch(i)
{
case 0: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo1"); break;
case 1: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo2"); break;
case 2: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo3"); break;
case 3: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo4"); break;
case 4: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo5"); break;
default: fileMemo = "";
}

String sql = " INSERT INTO info_upload (info_upload_id,sys_user_id,file_size,file_path,utime,deleted) "
+ " VALUES( " + Integer.toString(dinfo_upload_id) + "," + sys_user_id + "," + fileSize + ",'" + savePath + "', SYSDATE , 0 )" ;
sqlcmd cmd = new sqlcmd(con,sql);
//System.out.println(sql);
java.sql.PreparedStatement pstmt = null;
java.sql.Statement stmt = null;
//fileName = fileName.substring(0, fileName.indexOf("."));
String sql_cn = " UPDATE info_upload SET file_name=?,file_memo=? WHERE info_upload_id=? ";
java.io.ByteArrayInputStream bais_name = new java.io.ByteArrayInputStream(fileName.getBytes("ISO-8859-1"));
java.io.InputStreamReader isr_name = new java.io.InputStreamReader((InputStream)bais_name,"GBK");

java.io.ByteArrayInputStream bais_memo = new java.io.ByteArrayInputStream(fileMemo.getBytes("GBK"));
java.io.InputStreamReader isr_memo = new java.io.InputStreamReader((InputStream)bais_memo,"GBK");

try{
stmt = con.createStatement();
stmt.getConnection().setAutoCommit(false);

pstmt = con.prepareStatement(sql_cn);
pstmt.setCharacterStream(1, isr_name, fileName.length());
pstmt.setCharacterStream(2, isr_memo, fileMemo.length());
pstmt.setInt(3, dinfo_upload_id);

//System.out.println(sql_cn);

pstmt.execute();
stmt.executeUpdate("COMMIT");

}catch(Exception exce){
System.out.println(exce);
stmt.executeUpdate("ROLLBACK");
}
}
}
}catch(Exception e){
}


以上是jspsmart的方式,如果想要其它的方式,请下载全部源代码.



//upload_fileUpload.jsp

<%@ include file = "../../backgeneral.jsp"%>
<%@ contentType="text/html;charset=GBK" %>
<jsp:useBean id="userInfo" scope="session" class="com.ges.hbgov.UserInfo"/>
<%@ page import="org.apache.commons.fileupload.*" %>
<%
try{
 //request.setCharacterEncoding("GBK");
//取session 用户oid
    int pid = userInfo.getUserId();
    String sys_user_id = String.valueOf(pid);
//取init配置文件的参数值
 String sitePhysicalPath = (String)init.getObject("SitePhysicalPath");
 String saveDir  = (String)init.getObject("InfoUploadDir");
 String tempDir  = (String)init.getObject("InfoUploadDir");
 String fileMemo = "";    //文件说明
 String fileName = null;  //存储到数据库的文件名
 String saveName = null;  //存储到本地的文件名
 String filePath = null;  //存储到本地的文件路径
 String savePath = null;  //存储到数据库的文件路径
 long   fileSize = 0;     //文件大小
 int maxPostSize = -1;   
 int dinfo_upload_id = -1;
%>
<%
    DiskFileUpload df = new DiskFileUpload();
    //设定上传文件大小
 df.setSizeMax(maxPostSize);
 //设定临时目录
 df.setRepositoryPath(sitePhysicalPath + tempDir);
    //取得request信息
 List items = df.parseRequest(request);
   
 Iterator iter = items.iterator();
   
 int temp = 0;
 FileItem tempItem = null;

 while(iter.hasNext()){
  temp++;
  FileItem item = (FileItem)iter.next();
  if(item.isFormField())    //取得文件说明信息
  {
   fileMemo = item.getString("GBK");
   
  }
  else
  {   //取得上传文件信息
   fileName = (String)item.getName();
   try{
    fileName = fileName.substring(fileName.lastIndexOf("//")+1);
    fileName = fileName.substring(fileName.lastIndexOf("/")+1);
   }catch(Exception e){
    System.out.println(e);
   }
   fileSize = item.getSize();
   tempItem = item;
  }

  if(temp == 2 && fileSize != 0)
   {    //每两个iter存储一个上传文件

             //得到info_title_id
              String SQL_ID="select S_INFO_UPLOAD.nextval as seqid from dual";
           try {
                java.sql.Statement stmt = con.createStatement();
                java.sql.ResultSet rst= stmt.executeQuery(SQL_ID);
                while(rst.next())
       {
                       dinfo_upload_id = rst.getInt("seqid");
                }

             }catch(SQLException e1){
                    return;
             }
            //取得文件扩展名
            try{
    saveName = fileName.substring(fileName.lastIndexOf("."));
   }catch(Exception exc){
    saveName = "";
   }

            filePath = sitePhysicalPath + saveDir + Integer.toString(dinfo_upload_id) + saveName;
            //存储文件
   java.io.File uploadFile = new java.io.File(filePath);
   tempItem.write(uploadFile);
   /*try{
       FileOutputStream fos = new FileOutputStream(filePath);
       InputStream is = tempItem.getInputStream();
       byte[] b = new byte[1024];
       int nRead;
       long per = 0;
       double percent = 0;
                while((nRead = is.read(b, 0, 1024))>0){
        fos.write(b, 0, nRead);
        per += nRead;
        percent = (double)per/fileSize;

        session.setAttribute("percent",Double.toString(percent).substring(2,4));
        session.setAttribute("filename",fileName);
                }
       is.close();
    fos.close();    
    }catch(Exception e){
     System.out.println(e);
    }*/
            savePath = saveDir + Integer.toString(dinfo_upload_id) + saveName;
            /*/存储数据库
            String sql = " INSERT INTO info_upload (info_upload_id,sys_user_id,file_name,file_memo,file_size,file_path,utime,deleted) "
              + " VALUES( " + Integer.toString(dinfo_upload_id) + "," + sys_user_id + ",'" + fileName + "','" + fileMemo + "'," + fileSize + ",'" + savePath + "', SYSDATE , 0 )" ;
   sqlcmd cmd = new sqlcmd(con,sql);
   */
            String sql = " INSERT INTO info_upload (info_upload_id,sys_user_id,file_size,file_path,utime,deleted) "
              + " VALUES( " + Integer.toString(dinfo_upload_id) + "," + sys_user_id + "," + fileSize + ",'" + savePath + "', SYSDATE , 0 )" ;
   sqlcmd cmd = new sqlcmd(con,sql);
            //System.out.println(sql);
   java.sql.PreparedStatement pstmt = null;
   java.sql.Statement stmt = null;
   //fileName = fileName.substring(0, fileName.indexOf("."));
   String sql_cn = " UPDATE info_upload SET file_name=?,file_memo=? WHERE info_upload_id=? ";
   
   java.io.ByteArrayInputStream bais_name = new java.io.ByteArrayInputStream(fileName.getBytes("ISO-8859-1"));
   java.io.InputStreamReader isr_name = new java.io.InputStreamReader((InputStream)bais_name,"GBK");

   java.io.ByteArrayInputStream bais_memo = new java.io.ByteArrayInputStream(fileMemo.getBytes("GBK"));
   java.io.InputStreamReader isr_memo = new java.io.InputStreamReader((InputStream)bais_memo,"GBK");
   
   try{
    stmt = con.createStatement();
    stmt.getConnection().setAutoCommit(false);

    pstmt = con.prepareStatement(sql_cn);
    pstmt.setCharacterStream(1, isr_name, fileName.length());
    pstmt.setCharacterStream(2, isr_memo, fileMemo.length());
    pstmt.setInt(3, dinfo_upload_id);

                //System.out.println(sql_cn);

    pstmt.execute();
    stmt.executeUpdate("COMMIT");

   }catch(Exception exce){
    System.out.println(exce);
    stmt.executeUpdate("ROLLBACK");
   }

   temp = 0;
  }
  else if (temp == 2 && fileSize == 0) {temp = 0;}

 }
    //session.setAttribute("percent","ok");
}catch(Exception ex){
 System.out.println(ex);
}
response.sendRedirect("list.jsp");

%>




//upload_jspSmart.jsp

<%@ include file = "../../backgeneral.jsp"%>
<%@ page language="java" import="java.util.*,java.sql.*,java.io.*"%>
<%@ page language="java" import="com.jspsmart.upload.*"%>
<%@ page language="java" import="com.ges.hbgov.*"%>
<jsp:useBean id="userInfo" scope="session" class="com.ges.hbgov.UserInfo"/>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<%
//System.out.println("page=" + (String)session.getAttribute("SYS_USER_ID"));
if(!userInfo.Request(request)){
%>
<script language=javascript>
 function relogin() {
  this.parent.location.href="../../login.jsp";
 }
 relogin();
</script>
<%
}
%>

<%

try{
//取session 用户oid
    int pid = userInfo.getUserId();
    String sys_user_id = String.valueOf(pid);
//取init配置文件的参数值
 String sitePhysicalPath = (String)init.getObject("SitePhysicalPath");
 String saveDir  = (String)init.getObject("InfoUploadDir");
 String tempDir  = (String)init.getObject("InfoUploadDir");
 String fileMemo = "";    //文件说明
 String fileName = null;  //存储到数据库的文件名
 String saveName = null;  //存储到本地的文件名
 String filePath = null;  //存储到数据库的文件路径
 String savePath = null;  //存储到本地的文件路径
 long   fileSize = 0;     //文件大小
 int maxPostSize = -1;   
 int dinfo_upload_id = -1;
%>
<%
 //初始化
 mySmartUpload.initialize(pageContext);
 //上载文件
    mySmartUpload.upload();
 //循环取得所有上载文件
    for(int i=0; i<mySmartUpload.getFiles().getCount(); i++)
 {
  //取得上载文件
  com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i);
  if(!file.isMissing())
  {
   fileName = file.getFileName();
   //取得文件扩展名file.getFileExt()
   try{
    saveName = fileName.substring(fileName.lastIndexOf("."));

   }catch(Exception e){
    saveName = "";
   }
   //取得文件大小
   fileSize = file.getSize();
   //存储路径
   String sql_id = " SELECT S_INFO_UPLOAD.nextval as seqid FROM dual ";
   try{
    Statement stmt = con.createStatement();
    ResultSet rst = stmt.executeQuery(sql_id);
    while(rst.next())
    {
     dinfo_upload_id = rst.getInt("seqid");
    }
   }catch(SQLException sqle){
    return;
   }

   filePath = sitePhysicalPath + saveDir + Integer.toString(dinfo_upload_id) + saveName;
   savePath = saveDir + Integer.toString(dinfo_upload_id) + saveName;
   //存储文件到本地
   file.saveAs(filePath);
   //存储文件到数据库
   switch(i)
   {
    case 0: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo1"); break;
    case 1: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo2"); break;
                case 2: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo3"); break;
    case 3: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo4"); break;
    case 4: fileMemo = (String)mySmartUpload.getRequest().getParameter("memo5"); break;
    default: fileMemo = "";
   }

            String sql = " INSERT INTO info_upload (info_upload_id,sys_user_id,file_size,file_path,utime,deleted) "
              + " VALUES( " + Integer.toString(dinfo_upload_id) + "," + sys_user_id + "," + fileSize + ",'" + savePath + "', SYSDATE , 0 )" ;
   sqlcmd cmd = new sqlcmd(con,sql);
            //System.out.println(sql);
   java.sql.PreparedStatement pstmt = null;
   java.sql.Statement stmt = null;
   //fileName = fileName.substring(0, fileName.indexOf("."));
   String sql_cn = " UPDATE info_upload SET file_name=?,file_memo=? WHERE info_upload_id=? ";
   java.io.ByteArrayInputStream bais_name = new java.io.ByteArrayInputStream(fileName.getBytes("ISO-8859-1"));
   java.io.InputStreamReader isr_name = new java.io.InputStreamReader((InputStream)bais_name,"GBK");

   java.io.ByteArrayInputStream bais_memo = new java.io.ByteArrayInputStream(fileMemo.getBytes("GBK"));
   java.io.InputStreamReader isr_memo = new java.io.InputStreamReader((InputStream)bais_memo,"GBK");
   
   try{
    stmt = con.createStatement();
    stmt.getConnection().setAutoCommit(false);

    pstmt = con.prepareStatement(sql_cn);
    pstmt.setCharacterStream(1, isr_name, fileName.length());
    pstmt.setCharacterStream(2, isr_memo, fileMemo.length());
    pstmt.setInt(3, dinfo_upload_id);

                //System.out.println(sql_cn);

    pstmt.execute();
    stmt.executeUpdate("COMMIT");

   }catch(Exception exce){
    System.out.println(exce);
    stmt.executeUpdate("ROLLBACK");
   }
  }
 }
}catch(Exception e){
}

response.sendRedirect("list.jsp");
%>

posted on 2013-01-17 14:31 杨军威 阅读(1822) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜