上传下载后台函数以及前端脚本(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 ...
随机推荐
- 滑雪(简单dp)
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 81099 Accepted: 30239 Description Mic ...
- 并查集(加权) LA 4487 Exclusive-OR
题目传送门 题意:训练指南P245 分析:首先这道是经典的并查集题目,利用异或的性质.异或性质:x ^ 0 = x -> a ^ a = 0 -> x ^ a ^ a = x,即一个数对某 ...
- Wiki上的Ue4文件结构以及命名规范
https://wiki.unrealengine.com/Assets_Naming_Convention
- #ASP.NET Core 1.0 Key Features
Cross platform support and flexible runtime engine(跨平台支持和灵活的运行时引擎) ASP.NET Core 1.0 offers support f ...
- WPF:在ControlTemplate中使用TemplateBinding
A bit on TemplateBinding and how to use it inside a ControlTemplate. Introductio Today I'll try to w ...
- ACM: How many integers can you find-数论专题-容斥原理的简单应用+GCD
How many integers can you find Time Limit:5000MS Memory Limit:32768KB 64bit IO Format:%I64d ...
- 20145330《Java程序设计》第三周学习总结
20145330 <Java程序设计>第三周学习总结 第三周知识的难度已经逐步上升,并且一周学习两章学习压力也逐渐加大,需要更高效率的来完成学习内容,合理安排时间. 类与对象 对象(Obj ...
- hadoop编程小技巧(5)---自定义输入文件格式类InputFormat
Hadoop代码测试环境:Hadoop2.4 应用:在对数据需要进行一定条件的过滤和简单处理的时候可以使用自定义输入文件格式类. Hadoop内置的输入文件格式类有: 1)FileInputForma ...
- android 百度地图开发
package sposition.webjoy.net.sendposition; import android.os.Bundle; import android.support.design.w ...
- Eclispe怎么给工作空间下的项目分组
Eclispe怎么给工作空间下的项目分组 第一步,打开Java Working Set 第二步,添加分组 第三步,选择分组