Неожиданное завершение ошибки ввода JSON при загрузке файла с помощью jQuery File Upload - PullRequest
0 голосов
/ 01 января 2019

Я использую плагин загрузки файлов jQuery для загрузки документа / вложения на основной сервер asp.net.

при загрузке вложения я получил следующую ошибку Error SyntaxError: Unexpected end of JSON input

У меня ничего не изменилось, просто после демонстрационного проекта (Basic UI) jQuery File Upload ..

вот мой код JavaScript

$(function () {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = '/api/Document',
        uploadButton = $('<button/>')
            .addClass('btn btn-primary')
            .prop('disabled', false)
            .text('Progress..')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit().always(function () {
                    $this.remove();
                });
            });
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/)(gif|jpe?g|png|doc|docx|pdf|txt)$/i,
        maxFileSize: 999000,
        // 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) {
        data.context = $('<div/>').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<p/>')
                .append($('<span/>').text(file.name));
            if (!index) {
                node
                    .append('<br>')
                    .append(uploadButton.clone(true).data(data)).append('<hr/><br>');
            }
            node.appendTo(data.context);
        });
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append($('<span class="text-danger"/>').text(file.error));
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('Upload')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
            if (file.url) {
                var link = $('<a>')
                    .attr('target', '_blank')
                    .prop('href', file.url);
                $(data.context.children()[index])
                    .wrap(link);
            } else if (file.error) {
                var error = $('<span class="text-danger"/>').text(file.error);
                $(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});

, и это действие контроллера вызывается, когда кнопка загрузки click триггер события.

действие -

 [HttpPost]
    public async Task Post([FromForm]AddCommand command)
    {
        command.IsContactDoc = true;
        command.CreatedBy = Guid.Parse(_userManager.GetUserId(HttpContext.User));
        await _mediator.Send(command);
        return;
    }

далее больше ... во время отладки я также получил параметр командной строки как ноль.

пожалуйста, кто-нибудь объяснит мне, где я делаю ошибку..

1 Ответ

0 голосов
/ 02 января 2019

Вам необходимо сопоставить имя вашего входа с параметрами контроллера. Обратитесь к загружать файлы в ядро ​​asp.net .

<input id="fileupload" type="file" name="files" multiple>

Ваше действие:

[HttpPost]
public async Task Post([FromForm] List<IFormFile> files)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...