blueImp/jquery 文件上传 - 如果文件类型不被接受,我如何获得错误消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12506459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:46:17  来源:igfitidea点击:

blueImp/jquery file upload - How do I get the error message if the file type was not accepted?

jqueryblueimp

提问by JSBach

I want to use the BlueImp/Jquery File Upload to be able to upload some images to web webserver. I have this JS code which I generated by reading many sources

我想使用 BlueImp/Jquery 文件上传来将一些图像上传到网络服务器。我有这个 JS 代码,我通过阅读许多来源生成

 $('#file_upload').fileupload('option', {
        dataType: 'json',
        url: '/Upload/UploadFiles',
        maxFileSize: 5000000,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
        process: [
            {
                action: 'load',
                fileTypes: /^image\/(gif|jpeg|png)$/,
                maxFileSize: 20000000 // 20MB
            },
            {
                action: 'resize',
                maxWidth: 1440,
                maxHeight: 900
            },
            {
                action: 'save'
            }
        ],
        progressall: function (e, data) {
            $(this).find('.progressbar').progressbar({ value: parseInt(data.loaded / data.total * 100, 10) });
        },
        done: function (e, data) {
            $('#show_image').append('<img src="' + data.result[0].ThumbURL + '" />');
            $('#imgID').val($('#imgID').val() + data.result[0].Id + ',');
            $(this).find('.progressbar').progressbar({ value: 100 });
        },
        error: function (e, data) {
            var a = 1;
        }
    });
});

It works because it doesn't upload any file which is not an image, but I would like to be able to get the error messages (in case it exists) to show to the user.

它有效是因为它不上传任何不是图像的文件,但我希望能够获取错误消息(如果存在)以显示给用户。

In their demothey have some code (jquery.fileupload-ui.js and jquery.fileupload-fp.js) that create "magically" the HTML with the error inside (I am still strugling to understand it).

他们的演示中,他们有一些代码(jquery.fileupload-ui.js 和 jquery.fileupload-fp.js),它们“神奇地”创建了带有错误的 HTML(我仍在努力理解它)。

I don't really get if I should use these plugins too and somehow customize the HTML being generated or if it is simpler to get the info manually and populate it.

我真的不知道我是否也应该使用这些插件并以某种方式自定义正在生成的 HTML,或者手动获取信息并填充它是否更简单。

I am pretty new to JS and Jquery, so maybe I am missing something.

我对 JS 和 Jquery 很陌生,所以也许我错过了一些东西。

How do I configure the HTML being generated or how do I get the error message?

如何配置正在生成的 HTML 或如何获取错误消息?

Thanks, Oscar

谢谢,奥斯卡

采纳答案by Sameera Millavithanachchi

For this you can use file added callback to validate files, like this, use "return false" to avoid adding that file;

为此,您可以使用文件添加回调来验证文件,像这样,使用“返回假”来避免添加该文件;

 $('#yourfileuploader').fileupload({
                    add: function (e, data) {
                        var fileType = data.files[0].name.split('.').pop(), allowdtypes = 'jpeg,jpg,png,gif';
                        if (allowdtypes.indexOf(fileType) < 0) {
                            alert('Invalid file type, aborted');
                            return false;
                        }

                    }
                });

or you can register fileuploadadded callback like this,

或者你可以像这样注册 fileuploadAdded 回调,

$('#yourfileuploader').fileupload().bind('fileuploadadded', function (e, data) {
                    var fileType = data.files[0].name.split('.').pop(), allowdtypes = 'jpeg,jpg,png,gif';
                    if (allowdtypes.indexOf(fileType) < 0) {
                        alert('Invalid file type, aborted');
                        return false;
                    }
                });

also you can access fileupload acceptFileTypes options using; e.originalEvent.data.fileupload.options.acceptFileTypes

您也可以使用访问 fileupload acceptFileTypes 选项;e.originalEvent.data.fileupload.options.acceptFileTypes

You can find more information here;

您可以在这里找到更多信息;

https://github.com/blueimp/jQuery-File-Upload/wiki/Options

https://github.com/blueimp/jQuery-File-Upload/wiki/Options

回答by user2999209

I know this is an old thread, but if someone still looking for how to get the error message, here is a way to do it:

我知道这是一个旧线程,但如果有人仍在寻找如何获取错误消息,这里有一种方法:

$('#fileupload').bind('fileuploadprocessfail', function (e, data) {
    alert(data.files[data.index].error);
});

回答by Jonathan Pasquier

As mentioned by user2999209, the right way to go is with the fileuploadprocessfailcallback.

正如 user2999209 所提到的,正确的做法是使用fileuploadprocessfail回调。

To complete his answer, if you wish to translate the error message you should pass the following (undocumented) option:

要完成他的回答,如果您想翻译错误消息,您应该传递以下(未记录的)选项:

$('#my-uploader').fileupload({
    // ... some options ...
    messages : {
      maxNumberOfFiles: 'AAA Maximum number of files exceeded',
      acceptFileTypes: 'AAA File type not allowed',
      maxFileSize: 'AAA File is too large',
      minFileSize: 'AAA File is too small'
      uploadedBytes : 'AAA Uploaded bytes exceed file size'
    },
    // ... some other options ...
  })
  .on("fileuploadprocessfail", function(e, data) {
    var file = data.files[data.index];
    alert(file.error);
  });

Trying to upload a file with the wrong filetype will cause the message "AAA File type not allowed" to be displayed.

尝试上传文件类型错误的文件将导致显示消息“不允许 AAA 文件类型”。

回答by jchnxu

If you are using a PHP server, I have a simpler solution. If you are not, I believe this might help you as well.

如果您使用的是 PHP 服务器,我有一个更简单的解决方案。如果您不是,我相信这也可能对您有所帮助。

You don't need to use acceptFileTypes param in the frontend. Just initialize the PHP UploadHandler class with these params:

您不需要在前端使用 acceptFileTypes 参数。只需使用这些参数初始化 PHP UploadHandler 类:

array(
    'accept_file_types' => '/\.(gif|jpe?g|png)$/i',
    'upload_url' => 'uploads/', // both of upload_url, upload_dir equals to the upload destination
    'upload_dir' => 'uploads/',
    'max_file_size' => 1024*1024*2 // in byte
)

When you pass undesired file type or file size, The ajax return will be something like

当您传递不需要的文件类型或文件大小时,ajax 返回将类似于

{name: "Dream Come True.mp3", size: 14949044, type: "audio/mp3", error: "File type not allowed"} 

or

或者

{name: "feng (3).jpg", size: 634031, type: "image/jpeg", error: "File is too big"}

回答by Madhur

Use the processfailcallback

使用processfail回调

$('#fileupload').fileupload({
    maxFileSize: 5000000,
    done: function (e, data) {
        $.each(data.result.logo, function (index, file) {
            $('<p/>').text(file.name).appendTo('#fileupload-files');
        });
    },
    processfail: function (e, data) {
        alert(data.files[data.index].name + "\n" + data.files[data.index].error);
    }
});

回答by FAjir

The order you load scripts is importantto get the error message appear with default validation process,

加载脚本的顺序对于在默认验证过程中显示错误消息很重要

This order works for me :

这个顺序对我有用:

  1. tmpl.min.js
  2. jquery.ui.widget.js
  3. jquery.iframe-transport.js
  4. jquery.fileupload.js
  5. jquery.fileupload-ui.js
  6. jquery.fileupload-process.js
  7. jquery.fileupload-validate.js
  1. tmpl.min.js
  2. jquery.ui.widget.js
  3. jquery.iframe-transport.js
  4. jquery.fileupload.js
  5. jquery.fileupload-ui.js
  6. jquery.fileupload-process.js
  7. jquery.fileupload-validate.js

回答by Oleg Sh

It would be better to validate file type (it would be format like "image/jpeg") than extention. In this case you avoid potential problem with case-sensitive and similar unexpected troubles

验证文件类型(格式类似于“图像/jpeg”)会比扩展名更好。在这种情况下,您可以避免区分大小写和类似的意外问题的潜在问题

$('#yourfileuploader').fileupload().bind('fileuploadadded', function (e, data) {
                    var fileType = data.files[0].type;
                    if (type.indexOf('image') < 0) {
                        alert('Invalid file type, aborted');
                        return false;
                    }
                });

回答by Nick Res

Nothing I've found on in these answered worked for me, and strangely enough, the developers that wrote the demos for that plugin use a different style from whats described in the documentation. Anyway, that's aside from the point.

我在这些回答中发现的任何内容都不适合我,而且奇怪的是,为该插件编写演示的开发人员使用的风格与文档中描述的风格不同。无论如何,这不是重点。

I copied the code they use to get the UI version to work, and that finally did the trick for me. They use the .on method and 'processalways' to check for errors instead of using an 'error' or 'fail' method.

我复制了他们用来让 UI 版本工作的代码,这最终对我有用。他们使用 .on 方法和 'processalways' 来检查错误,而不是使用 'error' 或 'fail' 方法。

view-source:http://blueimp.github.io/jQuery-File-Upload/basic-plus.html

查看源:http: //blueimp.github.io/jQuery-File-Upload/basic-plus.html

Here's the source code.

这是源代码。

Cheers

干杯

回答by Talvi Watia

If you are new to understanding how javascript errorhandling works, it is best to read up on the topic: try/catch (MDN)

如果您不熟悉 javascript 错误处理的工作原理,最好阅读以下主题:try/catch (MDN)

However, the error is actually a method within the fileupload prototype, so theoretically this function will execute when the error happens.

但是,错误实际上是fileupload原型中的一个方法,所以理论上这个函数会在错误发生时执行。

Just add {your code} to the errorHandler in the method.

只需将 {your code} 添加到方法中的 errorHandler 即可。

...
error: function (e, data) {
        var a = 1; // <--in your example, this does nothing.
        alert(e); // <--or whatever you wish to do with the error
        return a; // <--did you want to return true?
    }
...

If this alert never happens, then no error is raised. The following code is normally how you catch them. (it doesn't do this already?)

如果此警报从未发生,则不会引发任何错误。以下代码通常是您捕获它们的方式。(它不是已经这样做了吗?)

try {

  ...any code you want to exception handle with...

  }
  catch (e) {      
    alert(e);
  }