jquery.uploadify-3.1+servlet实现多文件的上传和下载文件存储到BLOB中

来源:互联网 发布:利拉德数据 编辑:程序博客网 时间:2024/05/15 12:40

1.前台页面

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>upload.html</title>

    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<link rel="stylesheet" href="/cs/queryforjiankong/js/uploadify.css" type="text/css"></link>
<script type="text/javascript" src="/cs/queryforjiankong/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="/cs/queryforjiankong/js/jquery.uploadify-3.1.min.js"></script>
  </head>
  
  <body>
    <h1>Uploadify Demo</h1>
<div>
        <%--用来作为文件队列区域--%>
        <input type="text">
        <div id="fileQueue">
        </div>
        <input type="file" name="uploadify" id="uploadify" />
        <p>
            <a href="javascript:$('#uploadify').uploadify('upload')">上传</a>| 
            <a href="javascript:$('#uploadify').uploadify('cancel')">取消上传</a>
        </p>
      </div>



<script type="text/javascript">
$(function () {
            $("#uploadify").uploadify({
                //指定swf文件
                'swf': '/cs/queryforjiankong/js/uploadify.swf',
                //后台处理的页面
                'uploader': '/PicUpload',
                //按钮显示的文字
                'buttonText': '上传图片',
                //显示的高度和宽度,默认 height 30;width 120
                //'height': 15,
                //'width': 80,
                //上传文件的类型  默认为所有文件    'All Files'  ;  '*.*'
                //在浏览窗口底部的文件类型下拉菜单中显示的文本
                'fileTypeDesc': 'Image Files',
                //允许上传的文件后缀
                'fileTypeExts': '*.gif; *.jpg; *.png',
                //发送给后台的其他参数通过formData指定

//经测试这个数据在后台获取不到,我用了url传的参数
                //'formData': { 'someKey': 'someValue', 'someOtherKey': 1 },
                //上传文件页面中,你想要用来作为文件队列的元素的id, 默认为false  自动生成,  不带#
                'queueID': 'fileQueue',
                //选择文件后自动上传
                'auto': false,
                //设置为true将允许多文件上传
                'multi': true,
                 //上传成功后执行
                'onUploadSuccess': function (file, data, response) {

                    $('#' + file.id).find('.data').html(' 上传完毕');
                    
                 }
            });
        });
</script>
  </body>
</html>

2.后台处理上传的servlet的业务方法 我是把图片的信息存储到了数据库的BLOB字段中。

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map map = new HashMap();
String cr = System.getProperty("file.separator");
String path = request.getSession().getServletContext().getRealPath("/");
if(path.lastIndexOf(cr)==path.length() - 1){
path = path.substring(0,path.length() - 1);
}

request.setCharacterEncoding("utf-8");

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
  
    AnjianPDABean anjianPDABean =(AnjianPDABean) context.getBean("anjianPDABean");
String temp= path + cr + "se" + cr + "temp";   //临时目录

DiskFileUpload fu =new DiskFileUpload();

fu.setSizeMax(1*1024*1024*50);   // 设置允许用户上传文件大小,单位:字节

fu.setSizeThreshold(4096);   // 设置最多只允许在内存中存储的数据,单位:字节

fu.setRepositoryPath(temp);  // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录


//int index=0;业务处理service
BlobBL blobBL = (BlobBL)context.getBean("blobBL");
List fileItems =null;
//开始读取上传信息
try {
fileItems = fu.parseRequest(request);  // 对http请求消息进行解析

} catch (Exception e) {
e.printStackTrace();
}
Iterator iterator = fileItems.iterator(); // 依次处理每个上传的文件
ImageLob lob = null;
while (iterator.hasNext()){
FileItem item = (FileItem)iterator.next();  
//忽略其他不是文件域的所有表单信息  是否是普通表单字段
lob = new ImageLob(imageType);
if (!item.isFormField()){ 
String name = item.getName();  //获取上传文件名,包括路径
name=name.substring(name.lastIndexOf(cr)+1);   //从全路径中提取文件名
//  
// mobileBean.saveWentiPhoto(name);  //保存路径到数据库
String[] strings = name.split("-");
String filename= strings[0]; //记录id
 
long size = item.getSize();
if((name==null||name.equals("")) && size==0){
continue;
}

 
lob.setJlid(filename);//存储文件名
blobBL.saveImageLob(lob,item.get());

//存储上传的文件ID和文件名传给前台使用
                  map.put("fileName",name);
                 map.put("filePath",lob.getId());

}
}

        response.setContentType("text/xml; charset=UTF-8");
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("Pragma", "no-cache");
      PrintWriter out = response.getWriter();
      JSONObject jsonObject = JSONObject.fromObject(map);
      String msg =  jsonObject.toString();
      out.print(msg);
      out.close();
}

3.下载的servlet对应的业务方法

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = (String) request.getParameter("id");
ApplicationContext context = WebApplicationContextUtils
.getWebApplicationContext(request.getSession()
.getServletContext());
BlobBL blob = (BlobBL) context.getBean("blobBL");

if (id != null && !"".equals(id.trim())) {
ImageLob l = blob.getImageLob(new Integer(id.trim()));
BufferedInputStream is = null;
String fileName=l.getJlid();

//处理前台下载时文件名乱码问题
if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {  
fileName = URLEncoder.encode(fileName, "UTF-8");  
} else {  
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");  

// 清空response
            response.reset();
try {
SerializableBlob serializableBlob = (SerializableBlob) l.getImage();
            java.sql.Blob javablob = serializableBlob.getWrappedBlob() ;
is = new BufferedInputStream(javablob.getBinaryStream());
byte[] buffer = new byte[1024];
int length = 0;
// 设置response的Headerresponse
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
       response.addHeader("Content-Length", "" +is.available());
       OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
       response.setContentType("application/octet-stream");
while ((length = is.read(buffer)) > 0) {
toClient.write(buffer, 0, length);
//response.getOutputStream().write(buffer, 0, length);
}

           toClient.flush();
           toClient.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
is.close();
}


}
}


0 0
原创粉丝点击