上传下载后台函数以及前端脚本(webuploader) 备份

  1 import java.io.BufferedOutputStream;
  2 import java.io.IOException;
  3 import java.io.InputStream;
  4 import java.io.PrintWriter;
  5 import java.io.UnsupportedEncodingException;
  6 import java.net.URLEncoder;
  7 import java.util.HashMap;
  8 import java.util.List;
  9 import java.util.Map;
 10 import java.util.zip.ZipEntry;
 11 import java.util.zip.ZipOutputStream;
 12 
 13 import javax.mail.internet.MimeUtility;
 14 import javax.servlet.ServletOutputStream;
 15 import javax.servlet.http.HttpServletRequest;
 16 import javax.servlet.http.HttpServletResponse;
 17 
 18 import org.springframework.beans.factory.annotation.Autowired;
 19 import org.springframework.stereotype.Controller;
 20 import org.springframework.ui.Model;
 21 import org.springframework.web.bind.annotation.RequestMapping;
 22 import org.springframework.web.bind.annotation.RequestParam;
 23 import org.springframework.web.bind.annotation.ResponseBody;
 24 import org.springframework.web.multipart.MultipartFile;
 25 
 26 
 27 
 28 @Controller
 29 @RequestMapping("/commonUpload")
 30 public class CommonUploadContorller{
 31     
 32     @Autowired
 33     private CommonService centerCommonService;
 34     
 35     /**
 36      * 添加资料页
 37      * 
 38      * @return
 39      * @author guogf
 40      */
 41     @RequestMapping("/toUploadAttachment")
 42     public String toUploadAttachment(String blongId,String fileSource,Model model) {
 43         Map<String, Object> objMap = new HashMap<String, Object>();
 44         objMap.put("belongId", blongId);
 45         objMap.put("fileSource", fileSource);
 46         model.addAttribute("objMap", objMap);
 47         return "commonUpload/uploadAttachment";
 48     }
 49     
 50     @RequestMapping("/fileUpLoad")
 51     public String fileUpLoad(HttpServletRequest request,HttpServletResponse response,long belongId
 52             ,@RequestParam(defaultValue = "100") String fileSource, @RequestParam(value="file",required=false)MultipartFile file) {
 53         User currentUser = UserUtils.getUser();
 54         String attachmentId = centerCommonService.uploadAttachment(belongId,fileSource, file, currentUser);
 55         if(!"uploadError".equals(attachmentId)){
 56             try {
 57                 response.reset();
 58                 PrintWriter out = response.getWriter();
 59                 out.print("{\"attachmentId\" :"+ attachmentId+"}");
 60                 out.flush();
 61                 out.close();
 62             } catch (IOException e) {
 63                 // TODO Auto-generated catch block
 64                 e.printStackTrace();
 65             }
 66             return null;
 67         }else{
 68             return null;
 69         }
 70     }
 71     
 72     /**
 73      * 资料附件下载
 74      * @param files
 75      * @return
 76      * @author guogf
 77      */
 78     @RequestMapping("/downLoadAttachment")
 79     @ResponseBody
 80     public void downLoadAttachment(HttpServletRequest request,String attachId,HttpServletResponse response){
 81         FTPUtils ftpUtils = FTPUtils.getInstance();
 82         InputStream is = null;
 83         ServletOutputStream out;
 84         byte[] content = new byte[1024];
 85         String fileName = "";
 86         List<Attachment> attachList = centerCommonService.findAttList(attachId.split(","));
 87         if(attachList!=null && attachList.size()>1){//批量下载多个文件,先压缩,再下载
 88             try {
 89                 response.addHeader("Content-Disposition", "attachment; filename="+IdGen.getRandomName(6)+DateUtils.getNumberDateTime()+".zip");
 90                 ServletOutputStream sos=response.getOutputStream();
 91                 ZipOutputStream zipOut  = new ZipOutputStream(new BufferedOutputStream(sos)); 
 92                 int readLen = -1;
 93                 for(Attachment att : attachList){
 94                     ZipEntry entry = new ZipEntry(att.getFilePath()); 
 95                     zipOut.putNextEntry(entry);   
 96                     is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
 97                                     ,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
 98                     if(is!=null){
 99                         while ((readLen = is.read(content, 0, 1024)) != -1) {
100                             zipOut.write(content, 0, readLen);
101                         }
102                         is.close();   
103                     }
104                 }
105                 zipOut.close();
106             } catch (Exception e) {
107                 e.printStackTrace();
108             }
109         }else if(attachList!=null && attachList.size()==1){//下载单个文件,直接下载
110             Attachment att = attachList.get(0);
111             fileName = att.getFileName();
112             try {
113                 response.setHeader("Content-Type", "application/octet-stream");
114                 response.setHeader("X-Accel-Charset", "UTF-8");
115                 response.setHeader("Content-Disposition", "attachment;" + encode(request, fileName));
116                 is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
117                         ,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
118                 out = response.getOutputStream();
119                 int length = 0;
120                 while ((length = is.read(content)) != -1) {
121                     out.write(content, 0, length);
122                 }
123                 out.write(content);
124                 out.flush();
125                 out.close();
126             } catch (Exception e) {
127                 // TODO Auto-generated catch block
128                 e.printStackTrace();
129             }
130         }
131     }
132     
133     // IE与firefox下载区分
134     private String encode(HttpServletRequest request, String realfileName) {
135         String agent = request.getHeader("USER-AGENT").toLowerCase();
136         try {
137             String new_filename = URLEncoder.encode(realfileName, "UTF8");  
138             // IE
139             if (null != agent && -1 != agent.indexOf("msie")) {
140                 realfileName = URLEncoder.encode(realfileName, "UTF8")
141                         .replaceAll("\\+", "%20");
142                 realfileName ="filename="+ new String(realfileName.getBytes("GBK"),
143                         "iso-8859-1");
144                 // Firefox
145             } 
146          // Opera浏览器只能采用filename* 
147             else if (null != agent && agent.indexOf("opera") != -1) 
148             { 
149                 realfileName = "filename*=UTF-8''" + new_filename; 
150            } 
151            // Safari浏览器,只能采用ISO编码的中文输出 
152              else if (null != agent && agent.indexOf("safari") != -1 ) 
153              { 
154                  realfileName = "filename=\"" + new String(realfileName.getBytes("UTF-8"),"ISO8859-1") + "\""; 
155              } 
156              // Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出 
157              else if (null != agent && agent.indexOf("applewebkit") != -1 ) 
158               { 
159                 new_filename = MimeUtility.encodeText(realfileName, "UTF8", "B"); 
160                 realfileName = "filename=\"" + new_filename + "\""; 
161               } 
162              // FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出 
163             else if (null != agent && -1 != agent.indexOf("mozilla")) {
164 //                realfileName = MimeUtility
165 //                        .encodeText(realfileName, "UTF8", "B");
166                // realfileName = "filename=?UTF-8?B?" + (new String(Encodes.encodeBase64(realfileName.getBytes("UTF-8")))) + "?=";
167                 realfileName = "filename*=UTF-8''" + new_filename;  
168             }
169         } catch (UnsupportedEncodingException e) {
170             try {
171                 realfileName = new String(realfileName.getBytes("UTF-8"),
172                         "iso-8859-1");
173             } catch (UnsupportedEncodingException e1) {
174                 e1.printStackTrace();
175             }
176             e.printStackTrace();
177         }
178         return realfileName;
179     }
180 }
 var uploader;
    $(function(){
        //下面是文件上传的js操作
        var $ = jQuery,
        $list = $('#thelist'),
        $btn = $('#ctlBtn'),
        state = 'pending',
       
        uploader = WebUploader.create({
            // 不压缩image
            resize: false,
            // swf文件路径
            swf:  ctxStatic+'/WebUploader/Uploader.swf',
            // 文件接收服务端。
            server: ctx+'/commonUpload/fileUpLoad',
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            pick:{
                id:'#picker',
                multiple :true
            },
            formData: {
                belongId:$('#belongId').val(),
                fileSource:$('#fileSource').val()
            }
        });
        // 当有文件添加进来的时候
        uploader.on( 'fileQueued', function( file ) {
            $list.append( '<div id="' + file.id + '" class="item">' +
                '<h4 class="info">' + file.name + 
                '<a id="delete_' + file.id + '" class="file_close" title="删除" href="javascript:void(0);" fileId="" />'+'</h4>' +
                '<p class="state">等待上传...</p>' +
            '</div>' );
            $('#delete_'+ file.id).on('click',  function() {
                if($(this).attr("fileId")!=''){
                    var attachmentIds = $("#attachmentIds").val();
                    var arrList = attachmentIds.split(',');
                    arrList.splice($.inArray($(this).attr("fileId"),arrList),1); 
                    $("#attachmentIds").val(arrList.join(','));
                }
                $('#'+file.id).remove();
                uploader.removeFile( file );
            });
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');
            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                  '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                  '</div>' +
                '</div>').appendTo( $li ).find('.progress-bar');
            }
        
            $li.find('p.state').text('上传中');
        
            $percent.css( 'width', percentage * 100 + '%' );
        });
        uploader.on( 'uploadSuccess', function( file,response ) {
            var num = $('#attachmentIds').val();
            $('#attachmentIds').val(num+","+response.attachmentId);
            $( '#'+file.id ).find('p.state').text('已上传');
            $('#delete_'+ file.id).attr("fileId",response.attachmentId);
        });
        uploader.on( 'uploadError', function( file,reason ) {
            $( '#'+file.id ).find('p.state').text('上传出错');
        });
        uploader.on( 'uploadComplete', function( file ) {
            $( '#'+file.id ).find('.progress').fadeOut();
        });
        $btn.on( 'click', function() {
            if ( state === 'uploading' ) {
                uploader.stop();
            } else {
                uploader.upload();
            }
        });
        uploader.on( 'all', function( type ) {
            if ( type === 'startUpload' ) {
                state = 'uploading';
            } else if ( type === 'stopUpload' ) {
                state = 'paused';
            } else if ( type === 'uploadFinished' ) {
                state = 'done';
            }
        
            if ( state === 'uploading' ) {
                $btn.text('暂停上传');
            } else {
                $btn.text('开始上传');
            }
        });
    });
    var deleteFile = function(id){
        var attachmentIds = $("#attachmentIds").val();
        var arrList = attachmentIds.split(',');
        arrList.splice($.inArray(id,arrList),1); 
        $("#attachmentIds").val(arrList.join(','));
        $('#file_lable_'+id).remove();
    };

 

posted @ 2016-08-16 17:14  创业男生  阅读(1501)  评论(0编辑  收藏  举报