使用jquery文件上传验证文件?

时间:2015-03-13 12:13:44

标签: javascript jquery file-upload

我正在使用如下的jquery文件上传。

dialogElem.find('#upload-image-file-input').fileupload({
            url: url,
            dataType: 'json',
            autoUpload: true,
            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
            maxFileSize: 5000000, // 5 MB
            // Enable image resizing, except for Android and Opera,
            // which actually support image resizing, but fail to
            // send Blob objects via XHR requests:
            disableImageResize: /Android(?!.*Chrome)|Opera/
                .test(window.navigator.userAgent),
            previewMaxWidth: 100,
            previewMaxHeight: 100,
            previewCrop: true
        }).on('fileuploadadd', function (e, data) {
            var fileCount = data.originalFiles.length;
            if (fileCount > 5) {
                alert("The max number of files is : "+5);
                return false; 
            }
          }).on('fileuploadprocessalways', function (e, data) {
              //some logic
           }).on('fileuploadprogress', function (e, data) {
              //some logic
           }).on('fileuploaddone', function (e, data) {
              //some logic
            }).on('fileuploadfail', function (e, data) {
              //some logic
            })

fileuploadadd内,我添加了一些验证逻辑。如果验证失败,我该如何停止所有其他活动,例如fileuploadprogressfileuploadfailfileuploadprocessalways

2 个答案:

答案 0 :(得分:0)

如果你有一些像我几周前那样的任务 - 试试这个:

您可以通过中止XHR(ajax请求)调用来取消正在进行的上传。 您可以绑定到文件输入字段的fileuploadadd事件,在保留jqXHR对象的同时提交请求并将其用于中止:

jqXHR.abort();

例如:

$(".cloudinary-fileupload").bind('fileuploadadd', function(e, data) {
    jqXHR = data.submit(); // Catching the upload process of every file
});

$('#cancel_button').click(function (e) {
    if (jqXHR) {
        jqXHR.abort();  
        jqXHR = null;
        console.log("Canceled");
    }
    return false;
});

以下页面包含更多代码示例 https://github.com/blueimp/jQuery-File-Upload/issues/290

只需致电

if (fileCount > 5) { 
jqXHR.abort();  
jqXHR = null; }

答案 1 :(得分:0)

jqXHR.abort()对我不起作用。但抛出中止"添加"处理:

.bind('fileuploadadd', function (e, data) {
    if (total_uploads >= maxImagesPerPost){
        throw new Error('Upload maximum reached');
    }