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

上传下载后台函数以及前端脚本(webuploader) 备份的更多相关文章

  1. FTP上传下载文件(函数简易版)

    FTP上传下载文件(函数简易版) # 服务端 import socket import json import hashlib import struct import os user_dic = { ...

  2. java后台简单从阿里云上传下载文件并通知前端以附件的形式保存

    一. 首先开通阿里的OSS 服务 创建一个存储空间在新建一个Bucket 在你新建的bucket有所需的id和key 获取外网访问地址或者是内网 看个人需求 我使用的是外网(内网没用过 估计是部署到阿 ...

  3. Nginx + Lua搭建文件上传下载服务

    收录待用,修改转载已取得腾讯云授权 最新腾讯云技术公开课直播,提问腾讯W3C代表,如何从小白成为技术专家?点击了解活动详情 作者 | 庄进发 编辑 | 迷鹿 庄进发,信息安全部后台开发工程师,主要负责 ...

  4. nodejs+express-实现文件上传下载管理的网站

    Nodejs+Express-实现文件上传下载管理的网站 项目Github地址(对你有帮助记得给星哟):https://github.com/qcer/updo 后端:基于nodejs的express ...

  5. Android实现TCP断点上传,后台C#服务实现接收

    终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现,因为大多实现过断点下载.但稳定性不能保证, ...

  6. php实现文件上传下载功能小结

    文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...

  7. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  8. 实现TCP断点上传,后台C#服务实现接收

    实现TCP断点上传,后台C#服务实现接收 终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现, ...

  9. (转载)基于Bash命令行的百度云上传下载工具

    原文链接:http://hi.baidu.com/meoow/item/aef5814bbd5be3e1bcf451e9 这是我根据百度云PCS的API写的一个基于bash的命令行工具, 使用了cur ...

随机推荐

  1. 滑雪(简单dp)

    Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 81099   Accepted: 30239 Description Mic ...

  2. 并查集(加权) LA 4487 Exclusive-OR

    题目传送门 题意:训练指南P245 分析:首先这道是经典的并查集题目,利用异或的性质.异或性质:x ^ 0 = x -> a ^ a = 0 -> x ^ a ^ a = x,即一个数对某 ...

  3. Wiki上的Ue4文件结构以及命名规范

    https://wiki.unrealengine.com/Assets_Naming_Convention

  4. #ASP.NET Core 1.0 Key Features

    Cross platform support and flexible runtime engine(跨平台支持和灵活的运行时引擎) ASP.NET Core 1.0 offers support f ...

  5. WPF:在ControlTemplate中使用TemplateBinding

    A bit on TemplateBinding and how to use it inside a ControlTemplate. Introductio Today I'll try to w ...

  6. ACM: How many integers can you find-数论专题-容斥原理的简单应用+GCD

    How many integers can you find Time Limit:5000MS     Memory Limit:32768KB     64bit IO Format:%I64d ...

  7. 20145330《Java程序设计》第三周学习总结

    20145330 <Java程序设计>第三周学习总结 第三周知识的难度已经逐步上升,并且一周学习两章学习压力也逐渐加大,需要更高效率的来完成学习内容,合理安排时间. 类与对象 对象(Obj ...

  8. hadoop编程小技巧(5)---自定义输入文件格式类InputFormat

    Hadoop代码测试环境:Hadoop2.4 应用:在对数据需要进行一定条件的过滤和简单处理的时候可以使用自定义输入文件格式类. Hadoop内置的输入文件格式类有: 1)FileInputForma ...

  9. android 百度地图开发

    package sposition.webjoy.net.sendposition; import android.os.Bundle; import android.support.design.w ...

  10. Eclispe怎么给工作空间下的项目分组

    Eclispe怎么给工作空间下的项目分组 第一步,打开Java Working Set 第二步,添加分组 第三步,选择分组