您的位置:首页 > 其它

smartupload.jar 实现文件上传下载

2014-06-17 15:59 501 查看
【上传】

前台:

<form action="uploadimage.jsp" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="上传">
</form>


注意一点就是 enctype 是必须要的,否则会出乱子

sercice servlet:

package com.Gavin.tools.fileupload;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * **********************************************
 * @description 本例为上传照片及照片描述
 * @author Gavin.lee
 * @date Jun 14, 2009    9:18:40 AM
 * @version 1.0
 ***********************************************
 */
public class SmartUploadTest extends HttpServlet {    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
    
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String filePath = "front//photo//pic//";
        String messages="";
        String forward="";
        
        SmartUpload su = new SmartUpload();    
        long maxsize = 2 * 1024 * 1024;                                     // 设置每个上传文件的大小,为2MB
        String allowedFilesList = "jpg,gif,bmp";
        String denidFilesList = "exe,bat,jsp,htm,html,,";
        
        try {
            su.initialize(this.getServletConfig(), request, response);        //初始化
            su.setMaxFileSize(maxsize);                                     // 限制上传文件的大小
            su.setAllowedFilesList(allowedFilesList);                        // 设置允许上传的文件类型
            su.setDeniedFilesList(denidFilesList);   
            su.upload();                                                    // 上传文件
            
            String photoInfo = su.getRequest().getParameter("info");        //必须这样来获取request
            if(photoInfo==null||photoInfo.equals("")){                        //验证照片描述信息,若没有输入,则提示输入照片描述信息
                messages="请输入照片描述信息!";
                forward="/admin/error.jsp";
            }else{
                File file = su.getFiles().getFile(0);                        // 获取上传的文件,因为只上传了一个文件,所以可直接获取            
                if (!file.isMissing()) {                                     // 如果选择了文件
                    String now = new Date().getTime() + "";                    //获取当前时间并格式化为字符串
                    String photoAddr=filePath + now + "."+file.getFileExt();        //filePath值
                    
                    file.saveAs(photoAddr,File.S***EAS_VIRTUAL);            
                }else{
                    messages="请选择要上传的文件!";
                    forward="/admin/error.jsp";
                }                
            }            
        }catch (java.lang.SecurityException e){
            messages="<li>上传文件失败!上传的文件类型只允许为:jpg,gif,bmp</li>";
            forward="/admin/error.jsp";            
        }catch (SmartUploadException e) {
            messages="上传文件失败!";
            forward="/admin/error.jsp";
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }                
        request.setAttribute("messages",messages);        
        request.getRequestDispatcher(forward).forward(request, response);
    }

}


【下载】

下载其实跟我上一篇文章 commons-upload 下载道理所差无几
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class FileDownloadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {
        
        
        
        String filename = request.getParameter("file_name");
        
        if (filename == null)
            filename = "";
        
        filename = filename.trim();

        InputStream inStream = null;
        String attchname = "";

        byte[] b = new byte[100];
        int len = 0;
        try {            
            attchname = getAttachName(filename);    //取得附件的名称
            filename = getRealName(request, filename);    //取得附件的全路径
            
            if (filename == null) {
                System.out.println("文件不存在,或者禁止下载");
                return;
            }
            attchname = toUtf8String(attchname);    //将文件转码 UTF-8
            inStream = new FileInputStream(filename);
            response.reset();    //必须reset,否则会出现文件不完整
            
            SmartUpload su = new SmartUpload();    // 新建一个SmartUpload对象
            
            su.initialize(this.getServletConfig(), request, response);    // 初始化
            // 设定contentDisposition为null以禁止浏览器自动打开文件,
            //保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
            //doc时,浏览器将自动用word打开它。扩展名为pdf时,
            //浏览器将用acrobat打开。
            su.setContentDisposition(null);            
            su.downloadFile(filename);        // 下载文件            
            
            //循环取出流中的数据 
            while ((len = inStream.read(b)) > 0) {
                response.getOutputStream().write(b, 0, len);
            }
            inStream.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //取得附件的名称
    public static String getAttachName(String filename) {
        if (filename == null)
            return "";
        filename = filename.trim();
        int pos = 0;
        
        pos = filename.lastIndexOf("//");        
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }        
        
        pos = filename.lastIndexOf("/");        
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }
        
        pos = filename.lastIndexOf(File.separator);        
        if (pos > -1) {
            filename = filename.substring(pos + 1);
        }
        
        return filename;
    }

    //UTF8转码
    public static String toUtf8String(String string) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0)
                        k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        String s_utf8 = sb.toString();
        sb.delete(0, sb.length());
        sb.setLength(0);
        sb = null;
        return s_utf8;
    }

    //取得下载文件的真实全路径名称
    private String getRealName(HttpServletRequest request, String filename) {
        if (request == null || filename == null)
            return null;
        filename = filename.trim();
        if (filename.equals(""))
            return null;

        String filepath = request.getRealPath(filename);
        if (filepath == null)
            return null;
        File file = new File(filepath);
        if (!file.exists())
            return null;
        return filepath;
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {        
        this.doPost(request, response);
    }

}


这篇文章介绍了JspSmartUpload的主要类和方法的使用说明,摘自csdn
File类  
这个类包装了一个上传文件的所有信息。通过它,可以得到上传文件的文件名、文件大小、扩展名、文件数据等信息。  
File类主要提供以下方法:
1、saveAs作用:将文件换名另存。
原型: public void saveAs(J***A.lang.String destFilePathName)
或 public void saveAs(J***A.lang.String destFilePathName, int optionSaveAs)
其中,destFilePathName是另存的文件名,optionSaveAs是另存的选项,该选项有三个值,分别是S***EAS_PHYSICAL,S***EAS_VIRTUAL,S***EAS_AUTO。
S***EAS_PHYSICAL表明以操作系统的根目录为文件根目录另存文件,
S***EAS_VIRTUAL表明以Web应用程序的根目录为文件根目录另存文件,
S***EAS_AUTO则表示让组件决定,当Web应用程序的根目录存在另存文件的目录时,它会选择S***EAS_VIRTUAL,否则会选择S***EAS_PHYSICAL。
例如,saveAs("/upload/sample.zip",S***EAS_PHYSICAL)执行后若Web服务器安装在C盘,则另存的文件名实际是c:/uploadsample.zip。
而saveAs("/upload/sample.zip",S***EAS_VIRTUAL)执行后若Web应用程序的根目录是webapps/JSPsmartupload,则另存的文件名实际是webapps/PsmJSartupload/upload/sample.zip。
saveAs("/upload/sample.zip",S***EAS_AUTO)执行时若Web应用程序根目录下存在upload目录,则其效果同saveAs("/upload/sample.zip",S***EAS_VIRTUAL),否则同saveAs("/upload/sample.zip",S***EAS_PHYSICAL)。建议:对于Web程序的开发来说,最好使用S***EAS_VIRTUAL,以便移植。
2、isMissing 作用:这个方法用于判断用户是否选择了文件,也即对应的表单项是否有值。选择了文件时,它返回false。未选文件时,它返回true。
原型:public boolean isMissing()
3、getFieldName 作用:取HTML表单中对应于此上传文件的表单项的名字。
原型:public String getFieldName()
4、getFileName 作用:取文件名(不含目录信息)
原型:public String getFileName()
5、getFilePathName 作用:取文件全名(带目录)
原型:public String getFilePathName
6、getFileExt 作用:取文件扩展名(后缀)
原型:public String getFileExt()
7、getSize 作用:取文件长度(以字节计)
原型:public int getSize()
8、getBinaryData 作用:取文件数据中指定位移处的一个字节,用于检测文件等处理。
原型:public byte getBinaryData(int index)。其中,index表示位移,其值在0到getSize()-1之间。

㈡ Files类  这个类表示所有上传文件的集合,通过它可以得到上传文件的数目、大小等信息。有以下方法:
1、getCount 作用:取得上传文件的数目。
原型:public int getCount()
2、getFile 作用:取得指定位移处的文件对象File(这是com.JSPsmart.upload.File,不是J***A.io.File,注意区分)。
原型:public File getFile(int index)。其中,index为指定位移,其值在0到getCount()-1之间。
3、getSize 作用:取得上传文件的总长度,可用于限制一次性上传的数据量大小。原型:public long getSize()
4、getCollection 作用:将所有上传文件对象以Collection的形式返回,以便其它应用程序引用,浏览上传文件信息。
原型:public Collection getCollection()

5、getEnumeration 作用:将所有上传文件对象以Enumeration(枚举)的形式返回,以便其它应用程序浏览上传文件信息。
原型:public Enumeration getEnumeration()

㈢ Request类  这个类的功能等同于JSP内置的对象Request。只所以提供这个类,是因为对于文件上传表单,通过Request对象无法获得表单项的值,必须通过JSPSmartUpload组件提供的Request对象来获取。
该类提供如下方法:
1、getParameter 作用:获取指定参数之值。当参数不存在时,返回值为null。
原型:public String getParameter(String name)。其中,name为参数的名字。
2、getParameterValues 作用:当一个参数可以有多个值时,用此方法来取其值。它返回的是一个字符串数组。当参数不存在时,返回值为null。
原型:public String[] getParameterValues(String name)。其中,name为参数的名字。
3、getParameterNames 作用:取得Request对象中所有参数的名字,用于遍历所有参数。它返回的是一个枚举型的对象。
原型:public Enumeration getParameterNames()

(四) SmartUpload类 这个类完成上传下载工作。
A.上传与下载共用的方法:
只有一个:initialize。作用:执行上传下载的初始化工作,必须第一个执行。
原型:有多个,主要使用下面这个:
public final void initialize(J***Ax.servlet.JSP.PageContext pageContext)
其中,pageContext为JSP页面内置对象(页面上下文)。
B.上传文件使用的方法:
1、upload 作用:上传文件数据。对于上传操作,第一步执行initialize方法,第二步就要执行这个方法。
原型:public void upload()
2、save 作用:将全部上传文件保存到指定目录下,并返回保存的文件个数。
原型:public int save(String destPathName)
和public int save(String destPathName,int option) 其中,
destPathName为文件保存目录,option为保存选项,它有三个值,分别是S***E_PHYSICAL,S***E_VIRTUAL和S***E_AUTO。(同File类的saveAs方法的选项之值类似)S***E_PHYSICAL指示组件将文件保存到以操作系统根目录为文件根目录的目录下,
S***E_VIRTUAL指示组件将文件保存到以Web应用程序根目录为文件根目录的目录下,
而S***E_AUTO则表示由组件自动选择。
注:save(destPathName)作用等同于save(destPathName,S***E_AUTO)。
3、getSize 作用:取上传文件数据的总长度原型:public int getSize()
4、getFiles 作用:取全部上传文件,以Files对象形式返回,可以利用Files类的操作方法来获得上传文件的数目等信息。
原型:public Files getFiles()
5、getRequest 作用:取得Request对象,以便由此对象获得上传表单参数之值。
原型:public Request getRequest()
6、setAllowedFilesList 作用:设定允许上传带有指定扩展名的文件,当上传过程中有文件名不允许时,组件将抛出异常。
原型:public void setAllowedFilesList(String allowedFilesList)
其中,allowedFilesList为允许上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想允许上传那些没有扩展名的文件,可以用两个逗号表示。
例如:setAllowedFilesList("doc,txt,,")将允许上传带doc和txt扩展名的文件以及没有扩展名的文件。
7、setDeniedFilesList 作用:用于限制上传那些带有指定扩展名的文件。若有文件扩展名被限制,则上传时组件将抛出异常。
原型:public void setDeniedFilesList(String deniedFilesList) 其中,deniedFilesList为禁止上传的文件扩展名列表,各个扩展名之间以逗号分隔。如果想禁止上传那些没有扩展名的文件,可以用两个逗号来表示。
例如:setDeniedFilesList("exe,bat,,")将禁止上传带exe和bat扩展名的文件以及没有扩展名的文件。8、setMaxFileSize 作用:设定每个文件允许上传的最大长度。
原型:public void setMaxFileSize(long maxFileSize) 其中,maxFileSize为为每个文件允许上传的最大长度,当文件超出此长度时,将不被上传。
9、setTotalMaxFileSize 作用:设定允许上传的文件的总长度,用于限制一次性上传的数据量大小。
原型:public void setTotalMaxFileSize(long totalMaxFileSize) 其中,totalMaxFileSize为允许上传的文件的总长度
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: