上传下载后台函数以及前端脚本(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 ...
随机推荐
- PHP 批量修改图片的名字
<?php // glob() 返回指定目录下的文件名以及目录 $arr = glob("img/*.jpg"); $time = time(); $i = 100001; ...
- 20145223《Java程序程序设计》第2周学习总结
20145223 <Java程序设计>第2周学习总结 教材学习内容总结 一: 1.基本的类型: (1)整数:short(2字节).int(4字节).long(8字节) (2)字节 byte ...
- SQL SERVER 和ACCESS的数据导入导出
//批量导入Access string filepath = Server.MapPath("student.mdb"); stri ...
- ural 1255. Graveyard of the Cosa Nostra
1255. Graveyard of the Cosa Nostra Time limit: 1.0 secondMemory limit: 64 MB There is a custom among ...
- Fault Tolerance —— Storm的故障容错性
——本文讲解了Storm故障容忍性(Fault-Tolerance)的设计细节:当Worker.节点.Nimbus或者Supervisor出现故障时是如何实现故障容忍性,以及Nimbus是否存在单点 ...
- word多级编号,如何让第一级为大写“一”,其他级别均为小写1.
自定义里面设置了第一级为大写,2级.3级首字跟着变为大写,是因为2.3级没有勾选"正规形式编号",如图:
- Codeforces Round #235 (Div. 2)C、Team
#include <iostream> #include <algorithm> using namespace std; int main(){ int n,m; cin & ...
- Js:DOM对象操作常用的方法和属性
- 瀑布流 &留言板
实例:瀑布流 留言板(一)瀑布流瀑布流实现原理分析1.ajax文件内容function ajax(method, url, data, success) { var xhr = null; ...
- TCP连接探测中的Keepalive和心跳包
TCP连接探测中的Keepalive和心跳包 tcp keepalive 心跳 保活 Linuxtcp心跳keepalive保活1. TCP保活的必要性 1) 很多防火墙等对于空闲socket自动关闭 ...