上传下载后台函数以及前端脚本(webuploader) 备份
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import javax.mail.internet.MimeUtility;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; @Controller
@RequestMapping("/commonUpload")
public class CommonUploadContorller{ @Autowired
private CommonService centerCommonService; /**
* 添加资料页
*
* @return
* @author guogf
*/
@RequestMapping("/toUploadAttachment")
public String toUploadAttachment(String blongId,String fileSource,Model model) {
Map<String, Object> objMap = new HashMap<String, Object>();
objMap.put("belongId", blongId);
objMap.put("fileSource", fileSource);
model.addAttribute("objMap", objMap);
return "commonUpload/uploadAttachment";
} @RequestMapping("/fileUpLoad")
public String fileUpLoad(HttpServletRequest request,HttpServletResponse response,long belongId
,@RequestParam(defaultValue = "100") String fileSource, @RequestParam(value="file",required=false)MultipartFile file) {
User currentUser = UserUtils.getUser();
String attachmentId = centerCommonService.uploadAttachment(belongId,fileSource, file, currentUser);
if(!"uploadError".equals(attachmentId)){
try {
response.reset();
PrintWriter out = response.getWriter();
out.print("{\"attachmentId\" :"+ attachmentId+"}");
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}else{
return null;
}
} /**
* 资料附件下载
* @param files
* @return
* @author guogf
*/
@RequestMapping("/downLoadAttachment")
@ResponseBody
public void downLoadAttachment(HttpServletRequest request,String attachId,HttpServletResponse response){
FTPUtils ftpUtils = FTPUtils.getInstance();
InputStream is = null;
ServletOutputStream out;
byte[] content = new byte[1024];
String fileName = "";
List<Attachment> attachList = centerCommonService.findAttList(attachId.split(","));
if(attachList!=null && attachList.size()>1){//批量下载多个文件,先压缩,再下载
try {
response.addHeader("Content-Disposition", "attachment; filename="+IdGen.getRandomName(6)+DateUtils.getNumberDateTime()+".zip");
ServletOutputStream sos=response.getOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(sos));
int readLen = -1;
for(Attachment att : attachList){
ZipEntry entry = new ZipEntry(att.getFilePath());
zipOut.putNextEntry(entry);
is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
if(is!=null){
while ((readLen = is.read(content, 0, 1024)) != -1) {
zipOut.write(content, 0, readLen);
}
is.close();
}
}
zipOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}else if(attachList!=null && attachList.size()==1){//下载单个文件,直接下载
Attachment att = attachList.get(0);
fileName = att.getFileName();
try {
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("X-Accel-Charset", "UTF-8");
response.setHeader("Content-Disposition", "attachment;" + encode(request, fileName));
is = ftpUtils.retrieveFile(att.getFilePath().substring(0, att.getFilePath().lastIndexOf("/"))
,att.getFilePath().split("/")[att.getFilePath().split("/").length-1]);
out = response.getOutputStream();
int length = 0;
while ((length = is.read(content)) != -1) {
out.write(content, 0, length);
}
out.write(content);
out.flush();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // IE与firefox下载区分
private String encode(HttpServletRequest request, String realfileName) {
String agent = request.getHeader("USER-AGENT").toLowerCase();
try {
String new_filename = URLEncoder.encode(realfileName, "UTF8");
// IE
if (null != agent && -1 != agent.indexOf("msie")) {
realfileName = URLEncoder.encode(realfileName, "UTF8")
.replaceAll("\\+", "%20");
realfileName ="filename="+ new String(realfileName.getBytes("GBK"),
"iso-8859-1");
// Firefox
}
// Opera浏览器只能采用filename*
else if (null != agent && agent.indexOf("opera") != -1)
{
realfileName = "filename*=UTF-8''" + new_filename;
}
// Safari浏览器,只能采用ISO编码的中文输出
else if (null != agent && agent.indexOf("safari") != -1 )
{
realfileName = "filename=\"" + new String(realfileName.getBytes("UTF-8"),"ISO8859-1") + "\"";
}
// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
else if (null != agent && agent.indexOf("applewebkit") != -1 )
{
new_filename = MimeUtility.encodeText(realfileName, "UTF8", "B");
realfileName = "filename=\"" + new_filename + "\"";
}
// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
else if (null != agent && -1 != agent.indexOf("mozilla")) {
// realfileName = MimeUtility
// .encodeText(realfileName, "UTF8", "B");
// realfileName = "filename=?UTF-8?B?" + (new String(Encodes.encodeBase64(realfileName.getBytes("UTF-8")))) + "?=";
realfileName = "filename*=UTF-8''" + new_filename;
}
} catch (UnsupportedEncodingException e) {
try {
realfileName = new String(realfileName.getBytes("UTF-8"),
"iso-8859-1");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
return realfileName;
}
}
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();
};
上传下载后台函数以及前端脚本(webuploader) 备份的更多相关文章
- FTP上传下载文件(函数简易版)
FTP上传下载文件(函数简易版) # 服务端 import socket import json import hashlib import struct import os user_dic = { ...
- java后台简单从阿里云上传下载文件并通知前端以附件的形式保存
一. 首先开通阿里的OSS 服务 创建一个存储空间在新建一个Bucket 在你新建的bucket有所需的id和key 获取外网访问地址或者是内网 看个人需求 我使用的是外网(内网没用过 估计是部署到阿 ...
- Nginx + Lua搭建文件上传下载服务
收录待用,修改转载已取得腾讯云授权 最新腾讯云技术公开课直播,提问腾讯W3C代表,如何从小白成为技术专家?点击了解活动详情 作者 | 庄进发 编辑 | 迷鹿 庄进发,信息安全部后台开发工程师,主要负责 ...
- nodejs+express-实现文件上传下载管理的网站
Nodejs+Express-实现文件上传下载管理的网站 项目Github地址(对你有帮助记得给星哟):https://github.com/qcer/updo 后端:基于nodejs的express ...
- Android实现TCP断点上传,后台C#服务实现接收
终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现,因为大多实现过断点下载.但稳定性不能保证, ...
- php实现文件上传下载功能小结
文件的上传与下载是项目中必不可少的模块,也是php最基础的模块之一,大多数php框架中都封装了关于上传和下载的功能,不过对于原生的上传下载还是需要了解一下的.基本思路是通过form表单post方式实现 ...
- 2013第38周日Java文件上传下载收集思考
2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...
- 实现TCP断点上传,后台C#服务实现接收
实现TCP断点上传,后台C#服务实现接收 终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现, ...
- (转载)基于Bash命令行的百度云上传下载工具
原文链接:http://hi.baidu.com/meoow/item/aef5814bbd5be3e1bcf451e9 这是我根据百度云PCS的API写的一个基于bash的命令行工具, 使用了cur ...
随机推荐
- Zepto tap 穿透bug
当两个层重叠在一起时,使用Zepto的tap事件时,点击上面的一层时会触发下面一层的事件,特别是底层如果是input框时,必“穿透”,“google”说原因是“tap事件实际上是在冒泡到body上时才 ...
- kafka 集群安装与安装测试
一.集群安装 1. Kafka下载:wget https://archive.apache.org/dist/kafka/0.8.1/kafka_2.9.2-0.8.1.tgz 解压 tar zxvf ...
- WPF拖放功能实现zz
写在前面:本文为即兴而作,因此难免有疏漏和词不达意的地方.在这里,非常期望您提供评论,分享您的想法和建议. 这是一篇介绍如何在WPF中实现拖放功能的短文. 首先要读者清楚的一件事情是:拖放主要分为拖放 ...
- Image Transformation in WPF输入日志标题
Image transformation is a process of rotating and scaling images. Rotating Images There are two ways ...
- (转)MySQL提示“too many connections”的解决办法
link:http://www.cfp8.com/mysql-prompt-too-many-connections-solution.html 今天生产服务器上的MySQL出现了一个不算太陌生的错误 ...
- Spring MVC Rest 支持CORS
新建cors filter文件, package cn.ac.iscas.pebble.ufe.tools; import java.io.IOException; import javax.serv ...
- Android入门第八篇之GridView(九宫图)
本文来自http://blog.csdn.net/hellogv/ GridView跟ListView都是比较常用的多控件布局,而GridView更是实现九宫图的首选!本文就是介绍如何使用GridVi ...
- [Cocos2d-x For WP8]矩形碰撞检测
在游戏中我们通常会涉及到两个精灵之间的碰撞的计算,那么在Cocos2d-x里面我们通常会用矩形碰撞检测来计算两个精灵在运动的过程中是否碰撞到了.原理很简单,就是当运动的时候通过精灵的矩形坐标进行遍历来 ...
- 【BZOJ3122】【SDoi2013】随机数生成器
Description Input 输入含有多组数据,第一行一个正整数T,表示这个测试点内的数据组数. 接下来T行,每行有五个整数p,a,b,X1,t,表示一组数据.保证X1和t都是合法的页码. ...
- 定义 iOS 方法名等不错的规范
1.配置视图不应命名为 setxxxx, 而应叫做 showxxxx 2.让按钮高亮不应叫做 showxxx, 而应叫做 highlightedxxx. 3,弹出 toastView 可以用 show ...