smartupload

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.SAVEAS_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);
    }


}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.Gavin.tools.fileupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

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);
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值