文件分片上传-fastdfs-webuploader.js

  • 2018-11-26 19:41:17
  • 1522
  • 0


最近项目中用到了webuploader.js 文件分片上传到图片服务器(fastdfs),花费的时间比较久,这里记录下。


文件分片上传本质就是把一个文件分割成几个小文件,后台验证是否已存在,已上传的则跳过,然后把分片文件合并成一个文件


webuploader.js官网链接:


http://fex.baidu.com/webuploader/


java 后台验证:====


application.properties 配置文件存放路径


##分片文件保存地址
file.webupload.path=/webupload/files


WebUploadFileController.java


package com.ganjiangps.wangdaibus.webupload.controller;
import javax.ws.rs.FormParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ganjiangps.wangdaibus.common.controller.BaseController;
import com.ganjiangps.wangdaibus.common.response.ProcessBack;
import com.ganjiangps.wangdaibus.model.vo.CheckMd5FileVO;
import com.ganjiangps.wangdaibus.model.vo.UploadVO;
import com.ganjiangps.wangdaibus.webupload.service.WdbChunkUploadService;
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("webUploadFile")
public class WebUploadFileController extends BaseController{
 
@Autowired
private WdbChunkUploadService wdbChunkUploadService;
/**
 * 分片md5 验证
 * @param md5FileVO
 * @return
 */
@ResponseBody
@RequestMapping(value = "check", method = RequestMethod.POST)
public ProcessBack check(@FormParam("form-data") CheckMd5FileVO md5FileVO) {
 return wdbChunkUploadService.check(md5FileVO);
}
/**
 * 文件上传
 * @param file
 * @param uploadVO
 * @return
 */
@ResponseBody
@RequestMapping(value = "upload", method = RequestMethod.POST)
public ProcessBack upload(@RequestParam("file") MultipartFile file, @FormParam("form-data") UploadVO uploadVO) {
  Long chunk = uploadVO.getChunk();
if (chunk == null) {// 没有分片
return wdbChunkUploadService.UnChunkUpload(file, uploadVO);
} else {// 分片
ProcessBack back = wdbChunkUploadService.ChunkUpload(file, uploadVO);
 return back;
   }
}
}



WdbChunkUploadService.java  代码:



package com.ganjiangps.wangdaibus.webupload.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ganjiangps.wangdaibus.common.response.ProcessBack;
import com.ganjiangps.wangdaibus.common.util.FileUtil;
import com.ganjiangps.wangdaibus.model.vo.CheckMd5FileVO;
import com.ganjiangps.wangdaibus.model.vo.UploadVO;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.DefaultFastFileStorageClient;
/**
 * 
 * 网贷巴士 分片上传Service
 * @author admin
 *
 */
@Service
public class WdbChunkUploadService {
private static Logger LOG = LoggerFactory.getLogger(WdbChunkUploadService.class);
@Value("${file.webupload.path}")
private String WEBUPLOAD_PATH;
 
@Value("${wdbus.fdfs.url}")
private String hostUrl; //application.properties  配置的图片服务器域名
@Resource
private DefaultFastFileStorageClient defaultFastFileStorageClient;//图片上传工具类
private static final String Delimiter = "-";
/**
 * 上传之前校验(整个文件、分片)
 * 
 * @param md5FileVO
 * @return
 */
public ProcessBack check(CheckMd5FileVO md5FileVO) {
ProcessBack processBack = new ProcessBack();
Integer type = md5FileVO.getType();
Long chunk = md5FileVO.getChunk();
String fileName = md5FileVO.getFileName();
Long fileSize = md5FileVO.getFileSize();
if (type == 0) {// 未分片校验
String destfilePath = System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH   System.getProperty("file.separator")   fileName;
File destFile = new File(destfilePath);
if (destFile.exists() && destFile.length() == fileSize) {
processBack.setCode(ProcessBack.WEBUPLOAD_CODE_EXISTED);
processBack.setMessage("文件已存在,跳过");
return processBack;
} else {
processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("文件不存在");
return processBack;
 }
} else {// 分片校验
String fileMd5 = md5FileVO.getFileMd5();
String destFileDir = System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH   System.getProperty("file.separator")   fileMd5;
String destFileName = chunk   Delimiter   fileName;
String destFilePath = System.getProperty("java.io.tmpdir")   destFileDir   System.getProperty("file.separator")   destFileName;
File destFile = new File(destFilePath);
if (destFile.exists() && destFile.length() == fileSize) {
 processBack.setCode(ProcessBack.WEBUPLOAD_CODE_EXISTED);
processBack.setMessage("文件已存在,跳过");
return processBack;
} else {
 processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("分片不存在");
return processBack;
}
}
}
/**
 * 文件上传
 * 
 * @param file
 * @param uploadVO
 * @param appVersion
 * @return
 */
public ProcessBack upload(MultipartFile file, UploadVO uploadVO) {
Long chunk = uploadVO.getChunk();
if (chunk == null) {// 没有分片
return UnChunkUpload(file, uploadVO);
} else {// 分片
return ChunkUpload(file, uploadVO);
}
}
/**
 * 分片上传
 * 
 * @param file
 * @param uploadVO
 * @param appVersion
 * @return
 */
public ProcessBack ChunkUpload(MultipartFile file, UploadVO uploadVO) {
ProcessBack processBack = new ProcessBack();
String fileName = uploadVO.getName();
String fileMd5 = uploadVO.getFileMd5();
Long chunk = uploadVO.getChunk();// 当前片
Long chunks = uploadVO.getChunks();// 总共多少片
System.out.println("=====当前片===========" chunk);
System.out.println("=====总共多少片===========" chunks);
// 分片目录创建
String chunkDirPath = System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH   System.getProperty("file.separator")   fileMd5;
File chunkDir = new File(chunkDirPath);
if (!chunkDir.exists()) {
chunkDir.mkdirs();
}
// 分片文件上传
String chunkFileName = chunk   Delimiter   fileName;
String chunkFilePath = chunkDir    System.getProperty("file.separator")    chunkFileName;
File chunkFile = new File(chunkFilePath);
try {
file.transferTo(chunkFile);
} catch (Exception e) {
LOG.error("分片上传出错", e);
processBack.setCode(ProcessBack.FAIL_CODE);
processBack.setMessage("文件不存在");
return processBack;
 }
// 合并分片
Long chunkSize = uploadVO.getChunkSize();
long seek = chunkSize * chunk;
String destFilePath = System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH   System.getProperty("file.separator")   fileName;
File destFile = new File(destFilePath);
if (chunkFile.length() > 0) {
try {
FileUtil.randomAccessFile(chunkFile, destFile, seek);
} catch (IOException e) {
LOG.error("分片{}合并失败:{}", chunkFile.getName(), e.getMessage());
 processBack.setCode(ProcessBack.FAIL_CODE);
processBack.setMessage("分片合并失败");
return processBack;
}
}
/*//上传到本地
 if (chunk == chunks - 1) {
// 删除分片文件夹
FileUtil.deleteDirectory(chunkDirPath);
   processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传成功");
 return processBack;
 } else {
  processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传中...");
return processBack;
 }*/
//调用fastdfs 上传文件
StorePath storePath = null;
if (chunk == chunks - 1) {
// 删除分片文件夹
FileUtil.deleteDirectory(chunkDirPath);
   FileInputStream fileInputStream = null;
 try {
fileInputStream = FileUtils.openInputStream(destFile);
 //图片上传
storePath = defaultFastFileStorageClient.uploadFile(fileInputStream, destFile.length(), FilenameUtils.getExtension(destFile.getName()), null);
 } catch (IOException e) {
 e.printStackTrace();
 processBack.setCode(ProcessBack.FAIL_CODE);
 processBack.setMessage("上传失败");
 return processBack;
 }finally {
 if(fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
 e.printStackTrace();
}
}
  }
 
 //删除文件
FileUtil.deleteFile(destFilePath);
  if(storePath != null){
 processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传成功");
processBack.setData(this.hostUrl storePath.getFullPath());
return processBack;
}
  
  processBack.setCode(ProcessBack.FAIL_CODE);
processBack.setMessage("上传失败");
 return processBack;
 } else {
  processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传中...");
return processBack;
 }
}
/**
 * 未分片上传
 * 
 * @param file
 * @param uploadVO
 * @param appVersion
 * @return
 */
public ProcessBack UnChunkUpload(MultipartFile multipartFile, UploadVO uploadVO) {
ProcessBack processBack = new ProcessBack();
/*//本地上传
String fileName = uploadVO.getName();
// String fileMd5 = uploadVO.getFileMd5();
// 文件上传
File destFile = new File(System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH   File.separator   fileName);
if (multipartFile != null && !multipartFile.isEmpty()) {
// 上传目录
File fileDir = new File(System.getProperty("java.io.tmpdir")   WEBUPLOAD_PATH);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
if (destFile.exists()) {
destFile.delete();
}
try {
multipartFile.transferTo(destFile);
  processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传成功");
return processBack;
} catch (Exception e) {
LOG.error("文件上传出错", e);
 processBack.setCode(ProcessBack.FAIL_CODE);
processBack.setMessage("文件上传出错");
return processBack;
}
}*/
//上传到fastdfs 图片服务器
try {
StorePath storePath = defaultFastFileStorageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), 
FilenameUtils.getExtension(multipartFile.getOriginalFilename()), null);
if(storePath != null){
 processBack.setCode(ProcessBack.SUCCESS_CODE);
processBack.setMessage("上传成功");
processBack.setData(this.hostUrl storePath.getFullPath());
return processBack;
}
 } catch (IOException e) {
e.printStackTrace();
}
processBack.setCode(ProcessBack.FAIL_CODE);
processBack.setMessage("上传失败");
return processBack;
 }
}



ProcessBack.java 代码


package com.ganjiangps.wangdaibus.common.response;
/**
 * 系统内部业务方法处理返回对象
 */
public class ProcessBack {
    public static final String SUCCESS_CODE = "88";//成功状态码
    public static final String FAIL_CODE = "00";//失败状态码
    public static final String EXCEPTION_CODE = "22";//系统异常状态码
    public static final String USERNOTLOGIN = "99";//用户没有登陆-状态码
 
     
    public static final String WEBUPLOAD_CODE_EXISTED="1000000";//文件或分片已存在
      //other 其他请自己定义
    public static final String SUCCESS_MESSAGE = "操作成功";//成功返回描述
    public static final String FAIL_MESSAGE = "操作失败";//失败返回描述
    public static final String EXCEPTION_MESSAGE = "因网络响应不及时,请联系客服或重新操作";//异常返回描述
    private String code = ProcessBack.SUCCESS_CODE;//内部方法处理状态码
    private String message = ProcessBack.SUCCESS_MESSAGE;
    private Object data;
    public ProcessBack() {
    }
    public ProcessBack(String code) {
        this.code = code;
    }
    public ProcessBack(String code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }
}


UploadVO.java  代码:



package com.ganjiangps.wangdaibus.model.vo;
import java.util.Date;
/**
 * 文件上传VO
 *
 */
public class UploadVO {
/***
 * 文件id WU_FILE_0
 * 
 */
private String id;
/**
 * 文件名称 Beyond Compare.rar
 */
private String name;
/**
 * 类型 application/octet-stream
 */
private String type;
/**
 * 文件大小
 */
private Long size;
/**
 * 最后修改时间
 */
private Date lastModifiedDate;
/**
 * 分片片数
 */
private Long chunks;
/**
 * 当前分片标识
 */
private Long chunk;
/**
 * 分片设置大小
 */
private Long chunkSize;
/**
 * 表单数据
 */
private String formData;
/**
 * 文件Md5(文件的唯一标识)
 */
private String fileMd5;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Long getSize() {
return size;
}
public void setSize(Long size) {
this.size = size;
}
public Date getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Long getChunks() {
return chunks;
}
public void setChunks(Long chunks) {
this.chunks = chunks;
}
public Long getChunk() {
return chunk;
}
public void setChunk(Long chunk) {
this.chunk = chunk;
}
public String getFileMd5() {
return fileMd5;
}
public void setFileMd5(String fileMd5) {
this.fileMd5 = fileMd5;
}
public Long getChunkSize() {
return chunkSize;
}
public void setChunkSize(Long chunkSize) {
this.chunkSize = chunkSize;
}
public String getFormData() {
return formData;
}
public void setFormData(String formData) {
this.formData = formData;
}
}



CheckMd5FileVO.java  代码



package com.ganjiangps.wangdaibus.model.vo;
/**
 * 
 * 文件MD5校验VO
 */
public class CheckMd5FileVO {
/**
 * 0:不分片,1:分片
 */
private Integer type;
/**
 * 文件名
 */
private String fileName;
/**
 * 文件Md5(文件唯一表示)
 */
private String fileMd5;
/**
 * 当前分片下标
 */
private Long chunk;
/**
 * 文件大小(如果分片了,则是分片文件大小)
 */
private Long fileSize;
private String formData;
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileMd5() {
return fileMd5;
}
public void setFileMd5(String fileMd5) {
this.fileMd5 = fileMd5;
}
public Long getChunk() {
return chunk;
}
public void setChunk(Long chunk) {
this.chunk = chunk;
}
public Long getFileSize() {
return fileSize;
}
public void setFileSize(Long fileSize) {
this.fileSize = fileSize;
}
public String getFormData() {
return formData;
}
public void setFormData(String formData) {
this.formData = formData;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
}


js 配置============================


webuploader.js 配置分片验证:


WebUploader.Uploader.register({
'name': 'webUploaderHookCommand',
'before-send-file': 'beforeSendFile',
"before-send": "beforeSend"
}, {
beforeSendFile: function(file) {
var task = new WebUploader.Deferred();
fileName = file.name;
fileSize = file.size;
(new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function(percentage) {}).then(function(val) {
fileMd5 = val;
var url = checkUrl;
var data = {
type: 0,
fileName: fileName,
fileMd5: fileMd5,
fileSize: fileSize
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超时的话,只能认为该分片未上传过
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
file.statusText = 'server_error';
task.reject();
}
}).then(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data))
 if(data.code == "1000000") {
file.statusText = 'file_existed';
task.reject();
} else {
task.resolve();
} 
 });
});
return task.promise();
},
beforeSend: function(block) {
var task = new WebUploader.Deferred();
var url = checkUrl;
var data = {
type: 1,
fileName: fileName,
fileMd5: fileMd5,
chunk: block.chunk,
fileSize: block.end - block.start
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超时的话,只能认为该分片未上传过
dataType: "json"
}).then(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data))
if(data.code == "1000000") {
task.reject(); // 分片存在,则跳过上传
} else {
task.resolve();
}
});
this.owner.options.formData.fileMd5 = fileMd5;
this.owner.options.formData.chunkSize = chunkSize;
return task.promise();
}
});



webuploader.js 配置全部代码:

(function( $ ){
    // 当domReady的时候开始初始化
    $(function() {
        var $wrap = $('.uploader5'),
            // 图片容器
            $queue = $( '<ul class="filelist"></ul>' )
                .appendTo( $wrap.find( '.queueList5' ) ),
            // 状态栏,包括进度和控制按钮
            $statusBar = $wrap.find( '.statusBar5' ),
            // 文件总体选择信息。
            $info = $statusBar.find( '.info5' ),
            // 上传按钮
            $upload = $wrap.find( '.uploadBtn5' ),
            // 没选择文件之前的内容。
            $placeHolder = $wrap.find( '.placeholder5' ),
            $progress = $statusBar.find( '.progress5' ).hide(),
            
        //服务器路径
  checkUrl  = basePath   '/htmluser/preReplay/check',
uploadUrl = basePath   '/htmluser/preReplay/uploadimage',
              // 添加的文件数量
            fileCount = 0,
            // 添加的文件总大小
            fileSize = 0,
            // 优化retina, 在retina下这个值是2
            ratio = window.devicePixelRatio || 1,
            // 缩略图大小
            thumbnailWidth = 110 * ratio,
            thumbnailHeight = 110 * ratio,
            // 可能有pedding, ready, uploading, confirm, done.
            state = 'pedding',
            // 所有文件的进度信息,key为file id
            percentages = {},
            // 判断浏览器是否支持图片的base64
            isSupportBase64 = ( function() {
                var data = new Image();
                var support = true;
                data.onload = data.onerror = function() {
                    if( this.width != 1 || this.height != 1 ) {
                        support = false;
                    }
                }
                data.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
                return support;
            } )(),
            // 检测是否已经安装flash,检测flash的版本
            flashVersion = ( function() {
                var version;
                try {
                    version = navigator.plugins[ 'Shockwave Flash' ];
                    version = version.description;
                } catch ( ex ) {
                    try {
                        version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash')
                                .GetVariable('$version');
                    } catch ( ex2 ) {
                        version = '0.0';
                    }
                }
                version = version.match( /\d /g );
                return parseFloat( version[ 0 ]   '.'   version[ 1 ], 10 );
            } )(),
            supportTransition = (function(){
                var s = document.createElement('p').style,
                    r = 'transition' in s ||
                            'WebkitTransition' in s ||
                            'MozTransition' in s ||
                            'msTransition' in s ||
                            'OTransition' in s;
                s = null;
                return r;
            })(),
            // WebUploader实例
            uploader,
        //设置分片大小
chunkSize = 5 * 1024 * 1024,
// 文件名、文件MD5、文件大小、表单数据
fileName, fileMd5, fileSize, formData;
//不支持flash,并且是ie浏览器
        if ( !WebUploader.Uploader.support('flash') && WebUploader.browser.ie ) {
             // flash 安装了但是版本过低。
            if (flashVersion) {
                (function(container) {
                    window['expressinstallcallback'] = function( state ) {
                        switch(state) {
                            case 'Download.Cancelled':
                                alert('您取消了更新!')
                                break;
                            case 'Download.Failed':
                                alert('安装失败')
                                break;
                            default:
                                alert('安装已成功,请刷新!');
                                break;
                        }
                        delete window['expressinstallcallback'];
                    };
                    var swf = './expressInstall.swf';
                    // insert flash object
                    var html = '<object type="application/'  
                            'x-shockwave-flash" data="'    swf   '" ';
                    if (WebUploader.browser.ie) {
                        html  = 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ';
                    }
                    html  = 'width="100%" height="100%" style="outline:0">'   
                        '<param name="movie" value="'   swf   '" />'  
                        '<param name="wmode" value="transparent" />'  
                        '<param name="allowscriptaccess" value="always" />'  
                    '</object>';
                    container.html(html);
                })($wrap);
            // 压根就没有安转。
            } else {
                $wrap.html('<a href="http://www.adobe.com/go/getflashplayer" target="_blank" border="0"><img alt="get flash player" src="http://www.adobe.com/macromedia/style_guide/images/160x41_Get_Flash_Player.jpg" /></a>');
            }
            return;
        } else if (!WebUploader.Uploader.support()) {
            alert( 'Web Uploader 不支持您的浏览器!');
            return;
        }
        
        WebUploader.Uploader.register({
'name': 'webUploaderHookCommand',
'before-send-file': 'beforeSendFile',
"before-send": "beforeSend"
}, {
beforeSendFile: function(file) {
var task = new WebUploader.Deferred();
fileName = file.name;
fileSize = file.size;
(new WebUploader.Uploader()).md5File(file, 0, 10 * 1024 * 1024).progress(function(percentage) {}).then(function(val) {
fileMd5 = val;
var url = checkUrl;
var data = {
type: 0,
fileName: fileName,
fileMd5: fileMd5,
fileSize: fileSize
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超时的话,只能认为该分片未上传过
dataType: "json",
error: function(XMLHttpRequest, textStatus, errorThrown) {
file.statusText = 'server_error';
task.reject();
}
}).then(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data))
 if(data.code == "1000000") {
file.statusText = 'file_existed';
task.reject();
} else {
task.resolve();
} 
 });
});
return task.promise();
},
beforeSend: function(block) {
var task = new WebUploader.Deferred();
var url = checkUrl;
var data = {
type: 1,
fileName: fileName,
fileMd5: fileMd5,
chunk: block.chunk,
fileSize: block.end - block.start
};
$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
async: false, // 同步
timeout: 1000, // todo 超时的话,只能认为该分片未上传过
dataType: "json"
}).then(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data))
if(data.code == "1000000") {
task.reject(); // 分片存在,则跳过上传
} else {
task.resolve();
}
});
this.owner.options.formData.fileMd5 = fileMd5;
this.owner.options.formData.chunkSize = chunkSize;
return task.promise();
}
});
        // 实例化
        uploader = WebUploader.create({
            pick: {
                id: '#filePicker_5',
                label: '选择图片'
            },
            //携带额外参数
            formData: {
                uid: 123
            },
            dnd: '#dndArea',
            paste: '#uploader',
            swf: '../../dist/Uploader.swf',
            chunked: true,
            // 跨域时,是否允许携带cookie, 只有html5 runtime才有效
            withCredentials: true,
            chunkSize: chunkSize,
            chunkRetry: false,
            threads: 1,
            server: uploadUrl,
            // runtimeOrder: 'flash',
             accept: {
                 title: 'Images',
                 extensions: 'gif,jpg,jpeg,bmp,png',
                 mimeTypes: 'image/*'
             },
            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候,把图片打开。
            disableGlobalDnd: true,
            //限制多文件上传的个数
            fileNumLimit: 10,
            fileSizeLimit: 200 * 1024 * 1024,    // 200 M
            fileSingleSizeLimit: 50 * 1024 * 1024    // 50 M
        });
        // 拖拽时不接受 js, txt 文件。
        uploader.on( 'dndAccept', function( items ) {
            var denied = false,
                len = items.length,
                i = 0,
                // 修改js类型
                unAllowed = 'text/plain;application/javascript ';
            for ( ; i < len; i   ) {
                // 如果在列表里面
                if ( ~unAllowed.indexOf( items[ i ].type ) ) {
                    denied = true;
                    break;
                }
            }
            return !denied;
        });
        uploader.on('dialogOpen', function() {
            console.log('here');
        });
        // uploader.on('filesQueued', function() {
        //     uploader.sort(function( a, b ) {
        //         if ( a.name < b.name )
        //           return -1;
        //         if ( a.name > b.name )
        //           return 1;
        //         return 0;
        //     });
        // });
        // 添加“添加文件”的按钮,
        uploader.addButton({
            id: '#filePicker_n5',
            label: '继续添加'
        });
        uploader.on('ready', function() {
            window.uploader = uploader;
        });
        // 当有文件添加进来时执行,负责view的创建
        function addFile( file ) {
            var $li = $( '<li id="'   file.id   '">'  
                    '<p class="title">'   file.name   '</p>'  
                    '<p class="imgWrap"></p>' 
                    '<p class="progress"><span></span></p>'  
                    '</li>' ),
                $btns = $('<div class="file-panel">'  
                    '<span class="cancel">删除</span>'  
                    '<span class="rotateRight">向右旋转</span>'  
                    '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),
                $prgress = $li.find('p.progress span'),
                $wrap = $li.find( 'p.imgWrap' ),
                $info = $('<p class="error"></p>'),
                showError = function( code ) {
                    switch( code ) {
                        case 'exceed_size':
                            text = '文件大小超出';
                            break;
                        case 'interrupt':
                            text = '上传暂停';
                            break;
                        default:
                            text = '上传失败,请重试';
                            break;
                    }
                    $info.text( text ).appendTo( $li );
                };
             if ( file.getStatus() === 'invalid' ) {
                showError( file.statusText );
            } else {
                // @todo lazyload
                $wrap.text( '预览中' );
                uploader.makeThumb( file, function( error, src ) {
                    var img;
                    if ( error ) {
                        $wrap.text( '不能预览' );
                        return;
                    }
                    if( isSupportBase64 ) {
                        img = $('<img src="' src '">');
                        $wrap.empty().append( img );
                    } else {
                        $.ajax('../../server/preview.php', {
                            method: 'POST',
                            data: src,
                            dataType:'json'
                        }).done(function( response ) {
                            if (response.result) {
                                img = $('<img src="' response.result '">');
                                $wrap.empty().append( img );
                            } else {
                                $wrap.text("预览出错");
                            }
                        });
                    }
                }, thumbnailWidth, thumbnailHeight );
                percentages[ file.id ] = [ file.size, 0 ];
                file.rotation = 0;
            }
            file.on('statuschange', function( cur, prev ) {
                if ( prev === 'progress' ) {
                    $prgress.hide().width(0);
                } else if ( prev === 'queued' ) {
                    $li.off( 'mouseenter mouseleave' );
                    $btns.remove();
                }
                // 成功
                if ( cur === 'error' || cur === 'invalid' ) {
                    console.log( file.statusText );
                    showError( file.statusText );
                    percentages[ file.id ][ 1 ] = 1;
                } else if ( cur === 'interrupt' ) {
                    showError( 'interrupt' );
                } else if ( cur === 'queued' ) {
                    $info.remove();
                    $prgress.css('display', 'block');
                    percentages[ file.id ][ 1 ] = 0;
                } else if ( cur === 'progress' ) {
                    $info.remove();
                    $prgress.css('display', 'block');
                } else if ( cur === 'complete' ) {
                    $prgress.hide().width(0);
                    $li.append( '<span class="success"></span>' );
                }
                $li.removeClass( 'state-'   prev ).addClass( 'state-'   cur );
            });
            $li.on( 'mouseenter', function() {
                $btns.stop().animate({height: 30});
            });
            $li.on( 'mouseleave', function() {
                $btns.stop().animate({height: 0});
            });
            $btns.on( 'click', 'span', function() {
                var index = $(this).index(),
                    deg;
                switch ( index ) {
                    case 0:
                        uploader.removeFile( file );
                        return;
                    case 1:
                        file.rotation  = 90;
                        break;
                    case 2:
                        file.rotation -= 90;
                        break;
                }
                if ( supportTransition ) {
                    deg = 'rotate('   file.rotation   'deg)';
                    $wrap.css({
                        '-webkit-transform': deg,
                        '-mos-transform': deg,
                        '-o-transform': deg,
                        'transform': deg
                    });
                } else {
                    $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='  (~~((file.rotation/90)%4   4)%4)  ')');
                    // use jquery animate to rotation
                    // $({
                    //     rotation: rotation
                    // }).animate({
                    //     rotation: file.rotation
                    // }, {
                    //     easing: 'linear',
                    //     step: function( now ) {
                    //         now = now * Math.PI / 180;
                    //         var cos = Math.cos( now ),
                    //             sin = Math.sin( now );
                    //         $wrap.css( 'filter', "progid:DXImageTransform.Microsoft.Matrix(M11="   cos   ",M12="   (-sin)   ",M21="   sin   ",M22="   cos   ",SizingMethod='auto expand')");
                    //     }
                    // });
                }
            });
            $li.appendTo( $queue );
        }
        // 负责view的销毁
        function removeFile( file ) {
            var $li = $('#' file.id);
            delete percentages[ file.id ];
            updateTotalProgress();
            $li.off().find('.file-panel').off().end().remove();
        }
        function updateTotalProgress() {
            var loaded = 0,
                total = 0,
                spans = $progress.children(),
                percent;
            $.each( percentages, function( k, v ) {
                total  = v[ 0 ];
                loaded  = v[ 0 ] * v[ 1 ];
            } );
            percent = total ? loaded / total : 0;
            spans.eq( 0 ).text( Math.round( percent * 100 )   '%' );
            spans.eq( 1 ).css( 'width', Math.round( percent * 100 )   '%' );
            updateStatus();
        }
        function updateStatus() {
            var text = '', stats;
            if ( state === 'ready' ) {
                text = '选中'   fileCount   '张图片,共'  
                        WebUploader.formatSize( fileSize )   '。';
            } else if ( state === 'confirm' ) {
                stats = uploader.getStats();
                if ( stats.uploadFailNum ) {
                    text = '已成功上传'   stats.successNum  '张照片至XX相册,' 
                        stats.uploadFailNum   '张照片上传失败,<a class="retry" href="#">重新上传</a>失败图片或<a class="ignore" href="#">忽略</a>'
                }
            } else {
                stats = uploader.getStats();
                text = '共'   fileCount   '张('  
                        WebUploader.formatSize( fileSize )   
                        '),已上传'   stats.successNum   '张';
                if ( stats.uploadFailNum ) {
                    text  = ',失败'   stats.uploadFailNum   '张';
                }
            }
            $info.html( text );
        }
        function setState( val ) {
            var file, stats;
            if ( val === state ) {
                return;
            }
            $upload.removeClass( 'state-'   state );
            $upload.addClass( 'state-'   val );
            state = val;
            switch ( state ) {
                case 'pedding':
                    $placeHolder.removeClass( 'element-invisible' );
                    $queue.hide();
                    $statusBar.addClass( 'element-invisible' );
                    uploader.refresh();
                    break;
                case 'ready':
                    $placeHolder.addClass( 'element-invisible' );
                    $( '#filePicker_n5' ).removeClass( 'element-invisible');
                    $queue.show();
                    $statusBar.removeClass('element-invisible');
                    uploader.refresh();
                    break;
                case 'uploading':
                    $( '#filePicker_n5' ).addClass( 'element-invisible' );
                    $progress.show();
                    $upload.text( '暂停上传' );
                    break;
                case 'paused':
                    $progress.show();
                    $upload.text( '继续上传' );
                    break;
                case 'confirm':
                    $progress.hide();
                    $( '#filePicker_n5' ).removeClass( 'element-invisible' );
                    $upload.text( '开始上传' );
                    stats = uploader.getStats();
                    if ( stats.successNum && !stats.uploadFailNum ) {
                        setState( 'finish' );
                        return;
                    }
                    break;
                case 'finish':
                    stats = uploader.getStats();
                    if ( stats.successNum ) {
                       // alert( '上传成功' );
                    } else {
                        // 没有成功的图片,重设
                        state = 'done';
                        location.reload();
                    }
                    break;
            }
            updateStatus();
        }
        uploader.onUploadProgress = function( file, percentage ) {
            var $li = $('#' file.id),
                $percent = $li.find('.progress span');
            $percent.css( 'width', percentage * 100   '%' );
            percentages[ file.id ][ 1 ] = percentage;
            updateTotalProgress();
        };
        uploader.onFileQueued = function( file ) {
            fileCount  ;
            fileSize  = file.size;
            if ( fileCount === 1 ) {
                $placeHolder.addClass( 'element-invisible' );
                $statusBar.show();
            }
            addFile( file );
            setState( 'ready' );
            updateTotalProgress();
        };
        uploader.onFileDequeued = function( file ) {
            fileCount--;
            fileSize -= file.size;
            if ( !fileCount ) {
                setState( 'pedding' );
            }
            removeFile( file );
            updateTotalProgress();
        };
        uploader.on( 'all', function( type ) {
            var stats;
            switch( type ) {
                case 'uploadFinished':
                    setState( 'confirm' );
                    break;
                case 'startUpload':
                    setState( 'uploading' );
                    break;
                case 'stopUpload':
                    setState( 'paused' );
                    break;
            }
        });
        
        uploader.on( 'uploadError', function( file,response) {
     $("#"   file.id).parent().remove();
        });
       
        uploader.on( 'uploadSuccess', function( file,response) {
         if(response.code == "88"){//文件上传成功
        var imgsBox = $("#imgsBox").val();
        if(isEmpty(imgsBox)){
         imgsBox = response.data;
        }else{
        imgsBox  ="," response.data;
        }
        $("#imgsBox").val(imgsBox);
        }else{
        $("#"   file.id).parent().remove();
        }
            $( '#' file.id ).addClass('upload-state-success').find(".state").text("已上传"); 
        });
        uploader.onError = function( code ) {
            alert( 'Eroor: '   code );
        };
        $upload.on('click', function() {
            if ( $(this).hasClass( 'disabled' ) ) {
                return false;
            }
            if ( state === 'ready' ) {
                uploader.upload();
            } else if ( state === 'paused' ) {
                uploader.upload();
            } else if ( state === 'uploading' ) {
                uploader.stop();
            }
        });
        $info.on( 'click', '.retry', function() {
            uploader.retry();
        } );
        $info.on( 'click', '.ignore', function() {
            alert( 'todo' );
        } );
        $upload.addClass( 'state-'   state );
        updateTotalProgress();
         
    });
})( jQuery );


回复
举报
全部回复(0)

参与讨论