`
duanfei
  • 浏览: 722231 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

java中文件上传与下载

    博客分类:
  • J2EE
 
阅读更多
1。上传文件流程

先通过用户提交文件,保存文件到服务器端,然后在写入数据库中,每次到下载页面时从数据库中读出文件,生成文件在服务器目录中,以下。。。


文件上传后保存文件到服务器中jsp,

upFile.jsp

<%@ page contentType="text/html; charset=utf-8" language="java" %>
<%@page import="java.util.List;"%>

<html>
<head>
<title>上传文件</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<base target="_self">
<link href="Css/style.css" rel="stylesheet">
<script type="text/javascript">
    function check(){
        var file = document.getElementById("file1").value;
        if(file == ""){
          alert('请选择要上传的文件');
          return false;
         }else{
          window.returnValue=file;
          return true;
         }
       }
</script>
</head>
<body>
<%
String files=request.getParameter("files");
%>
<form name="form2" enctype="multipart/form-data" method="post" action="../MissionManage/commonfile.jsp?files=<%=files %>" onsubmit="return check();">
<center>
<table align="center" width="350" height="150" border="0" cellpadding="0" cellspacing="0"><!-- background="images/upFile_bg.gif -->
    <tr>
      <td valign="top"><table width="100%" height="145" border="0" cellpadding="0" cellspacing="0">
        <tr>
          <td height="49" colspan="2">&nbsp;</td>
        </tr>
        <tr>
          <td width="9%" height="53">&nbsp;</td>
          <td width="91%"><b>请选择上传的文件:</b><br>
            <input id="file1" name="file1" type="file" size="35" onkeydown="return false;">
            <br>
            注:文件大小请控制在10M以内。</td>
        </tr>
        <tr>
            <td colspan="2" align="center"><input name="Submit" type="submit" class="btn_grey" value="确认">
            &nbsp;
            <input name="Submit2" type="button" class="btn_grey" onClick="window.close()" value="关闭"></td>
        </tr>
      </table></td>
    </tr>
</table>
</center>
</form>
</body>
</html>


commonfile.jsp

<%@ page language="java" import="java.io.*" pageEncoding="UTF-8"%>
<%@page import="java.util.*,org.apache.commons.fileupload.FileItem" %>
<%@page import="java.text.SimpleDateFormat,java.util.Date" %>
<%@page import="com.PoliceSystem.tools.FileOperate" %>
<jsp:useBean id="factory" scope="page" class="org.apache.commons.fileupload.disk.DiskFileItemFactory" />
<jsp:useBean id="upload" scope="page" class="org.apache.commons.fileupload.servlet.ServletFileUpload" />
<%
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>上传文件</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">
<base target="_self">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" language="javascript">

    </script>
</head>

<body>
   <% 
     request.setCharacterEncoding("UTF-8"); 
     String path1 = (String)request.getRealPath("/upload1");
     
     String files=request.getParameter("files");
     String[] fileList=files.split(";");
     
     File file = new File(path1); 
   
if(!file.exists()){ 
     file.mkdirs(); 
} 
     factory.setRepository(file); 
     factory.setSizeThreshold(1024*1024); 
     
     upload.setFileItemFactory(factory);
        
     try{ 
     List<FileItem> list= upload.parseRequest(request); 

        for(FileItem item:list){ 
      if(item.isFormField()){ 
        //String value=item.getString("UTF-8"); 
        //session.setAttribute("fileName", value);        
      }else{ 
        String value=item.getName(); 
        int start=value.lastIndexOf("\\"); 
        String fileName=value.substring(start+1); 
        if(fileName.length() == 0 || fileName == ""){ 
            out.println("<script>alert('上传失败');window.close();</script>"); 
        }else{        
         if(item.getSize()>10000000){
           out.println("<script>alert('对不起,您上传的文件超过10M,无法完成上传!');window.close();</script>"); 
         }else{
           SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 
              Date date =new Date();
              String[] f = item.getName().split("\\\\");
              //System.out.println(f[f.length-1]);
              String oldFileName = f[f.length-1];
              for(int i=0;i<fileList.length;i++){
              if(fileList[i].indexOf(oldFileName)!=-1){
                 out.println("<script>alert('对不起,您上传的文件与现有上传的文件重名,请更换文件名重新上传!');window.returnValue='';window.close();</script>");
              }
              }
              String fType = FileOperate.getFileType(item.getName());//文件类型
           fileName = sdf.format(date)+"."+fType;//新文件名
           //System.out.println(item.getName()+"---"+fileName);
           item.write(new java.io.File(path1,fileName));
           //////--1--/////
           String mailFileNames = new String();
           String old = (String)session.getAttribute("fuJianFileNames");
        if(old!=null){
          mailFileNames = old;
        }
        mailFileNames+=oldFileName+"|"+fileName+";"; 
        //System.out.println("mailFileNames="+mailFileNames);    
        session.removeAttribute("fuJianFileNames");
        session.setAttribute("fuJianFileNames", mailFileNames); 
           //////--2--/////
           //String pathName = path1+"\\"+fileName;
           //System.out.println("pathName="+pathName);           
           out.println("<script>window.close();</script>"); 
         }
        }        
      }
        }
    }catch (Exception e) {
       e.printStackTrace();
       out.println("<script>window.close();</script>");
    }
   %>
</body>
</html>


插入文件数据到数据库中

public boolean insert_annex(String[] str){
   boolean b=true;
   String sql ="";
   con = db.getConn();
   try{
    sql="insert into annex (querykey,sfilename,committime,Filetype,filepath,pno,Annex) values (?,?,?,?,?,?,?)";
    ps = con.prepareStatement(sql);
    for(int i=0;i<str.length-1;i++){
     ps.setString(i+1, str[i]);
    }
    File file = new File(str[6]);//附件
   
    InputStream iso = new FileInputStream(file);
    ps.setBinaryStream(7, iso, iso.available());
    ps.execute();
    iso.close();
    System.out.println("删除临时文件:" + file.delete());// 删除tmp文件
   }catch(Exception e){
    b=false;
    e.printStackTrace();
   }finally{
    this.close();
   }
   return b;
}

读出文件数据,并保存

public boolean addTempFile_annex(String querykey,HttpServletRequest request){
   boolean b=true;
   con = db.getConn();
   InputStream in = null;
   OutputStream out= null;  
   String path1 = (String)request.getRealPath("/upload1");//文件下载临时目录
   try{
    String sql="select filePath,annex from annex where querykey='"+querykey+"'";
    //String sql_1="select annex from annex where querykey='"+querykey+"'";
   
    ps = con.prepareStatement(sql);
    rs=ps.executeQuery();
    while(rs.next()){
     File f = new File(path1+rs.getString("filepath"));
     in=rs.getBinaryStream("annex");
     out = new FileOutputStream(f);
     int len = 10 * 100 * 100; //定义字符数组长度
     byte[] P_Buf=new byte[len];
     int j;
       while((j=in.read(P_Buf))!=-1){
          out.write(P_Buf, 0, j);
          }
    }
    in.close();
            out.flush(); //强制清出缓冲区
            out.close();
   }catch(Exception e){
    b=false;
    e.printStackTrace();
   }finally{
    this.close();
   }
   return b;
}

给定传递过来的参数(文件名,文件存储在服务器的文件名,文件在服务器的路径,文件类型),下载文件Action

package com.PoliceSystem.action.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class downLoadFile extends ActionSupport{
private static final long serialVersionUID = -2207648627734251737L;

public String execute() throws Exception{
   HttpServletRequest request = ServletActionContext.getRequest();
   HttpServletResponse response = ServletActionContext.getResponse();
  
   String fileminitype = request.getParameter("fileType");
   String filename1 = new String(request.getParameter("fileName1").getBytes("ISO8859-1"),"UTF-8");
   String filename2 = new String(request.getParameter("fileName2").getBytes("ISO8859-1"),"UTF-8");
   String filepath = request.getRealPath("/upload1");
   File f = new File(filepath+"\\"+filename2);
   Long filelength = f.length();
   int cacheTime = 10;
  
   response.setContentType(fileminitype);
   response.setHeader("Location",filename1);
   response.setHeader("Cache-Control", "max-age=" + cacheTime);
  
   response.setContentType("application/octet-stream");
   byte[] b = filename1.getBytes("GBK");   
   filename1 = new String(b,"8859_1");   
   response.setHeader("Content-Disposition", "attachment;filename=" + filename1); 
   response.setContentLength(filelength.intValue());
   OutputStream outputStream = response.getOutputStream();
   InputStream inputStream = new FileInputStream(f);
   byte[] buffer = new byte[1024];
   int i = -1;
   while ((i = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, i);
   }
   
   outputStream.flush();
   outputStream.close();
   inputStream.close();
  
   return null ;
     }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics