上传下载后台函数以及前端脚本(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 ...
随机推荐
- hdu5432 二分
Pyramid Split Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Tot ...
- 把spring-boot项目部署到tomcat容器中
http://blog.csdn.net/javahighness/article/details/52515226
- Docker使用-v挂载主机目录到容器后出现Permission denied
1. 在挂载主机目录的到容器后,操作挂载的目录出现权限问题: # 将主机上的/data/share/master目录挂载到容器的/opt/share目录docker run -it --name=ma ...
- 疯狂java学习笔记之面向对象(二) - 成员变量与局部变量
Java变量按其作用域可分为:成员变量和局部变量.注意:在Java中是没有全局变量这个概念的 一.成员变量: 成员变量是在类中定义的变量,具体可分为类变量与实例变量--有无static修饰 实例变量的 ...
- C# 开发积累(1)
EntityFramework批量增加时报"...请在调用 AcceptChanges 之前,确保键值是唯一的" http://www.xinglongjian.com/i ...
- HDU4609 3-idiots(母函数 + FFT)
题目 Source http://acm.hdu.edu.cn/showproblem.php?pid=4609 Description King OMeGa catched three men wh ...
- ggplot2包--R可视化
1.ggplot2发展历程 ggplot2是Hadley在爱荷华州立大学博士期间的作品,也是他博士论文的主题之一,实际上ggplot2还有个前身ggplot,但后来废弃了,某种程度上这也是Hadley ...
- eclipse 高亮配对的括号
在编辑代码框右键->preference,直接就可以看到Matching brackets highlights
- React.js 常用技术要点
最近在公司的一个移动端WEB产品中使用了React这个框架(并不是React-Native),记录一下在开发过程中遇到的各种问题以及对应的解决方法,希望能对读者有所帮助. React原则 React不 ...
- 使用HTML 5捕捉音频与视频信息
长期以来,音频与视频信息的捕捉一直是Web开发中的一个难点.许多年来,我们一直依赖浏览器插件来实现这个需求. 在HTML 5中,出现了许多可以访问硬件设备的API,例如访问GPS设备的Geolocat ...