вложение большого файла через Angularjs - PullRequest
0 голосов
/ 05 декабря 2018

Ниже код был сгенерирован и подключен к контроллеру, называемому «потоковым» в ядре .net.Код работает хорошо и отлично прикрепляет большие файлы.Код необходимо использовать на другой html-странице для загрузки файлов для других целей.Однако при нажатии кнопки загрузки отображается ошибка ниже:

Не удалось загрузить ресурс: сервер ответил со статусом 400 (неверный запрос)

Это тот случай, когда я прикрепляю файл с исходной страницы,процесс завершается, и тогда я могу прикрепить любой файл со скопированной страницы!Но если я закрою браузер и попытаюсь прикрепить файл со скопированной страницы, появится сообщение об ошибке.

<div class="panel-body" ng-app="myApp">
    @*Attachment*@
    <div ng-app="myApp">
        <div ng-controller="myCtrl">
            <div>
                @if (ViewBag.Attachments != null)
                {
                    foreach (var a in ViewBag.Attachments)
                    {
                        var id = @a.AttachmentId;
                        @lastattachid = id;
                        <div class="row">
                            <div class="col-xs-12 left">
                                <a asp-action="Download" asp-route-path="@a.FilePath\\@a.FileName">@a.FileName</a>
                                <div style=" position: absolute;top: 2px;right: 2px;">
                                    @if (ViewBag.recepient.Equals(@a.CreatedBy))
                                    {
                                        var FilePath = @a.FilePath.Replace("\\", "\\\\");
                                        <a onclick='deleteattachment(@a.AttachmentId, "@a.FileName", "@FilePath")'>✘</a>
                                    }
                                </div>
                            </div>
                        </div>
                    }
                }
            </div>
            <hr />
            <div>
                <div>
                    <div>
                        <input name="attachedfile" type="file" file-model="attachedfile" />
                    </div>
                </div>
                <br />
                <div>
                    <button ng-click="uploadAttachment()">Upload</button>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>

<script>
       var Attachment = (function () {
           function Attachment(customer, invoice, name, dwg, attachedfile) {
               this.attachmentid = @lastattachid + 1;
               this.customer = customer;
               this.jobInv = invoice;
               this.jobName = name;
               this.jobDwg = dwg;
               this.path = "\\@ViewBag.customerId\\" + invoice + ";" + name + ";" + dwg + "\\";
               this.fileName = attachedfile.name;
               this.attachedfile = attachedfile;
           }
           return Attachment;
       }());
       var myApp = angular.module('myApp', []);
       myApp.directive('fileModel', ['$parse', function ($parse) {
           return {
               restrict: 'A',
               link: function (scope, element, attrs) {
                   var model = $parse(attrs.fileModel);
                   var modelSetter = model.assign;

                   element.bind('change', function () {
                       scope.$apply(function () {
                           modelSetter(scope, element[0].files[0]);
                       });
                   });
               }
           };
       }]);
       myApp.service('attachmentService', ['$http', function ($http) {
           this.uploadAttachment = function (attachment) {
               var fd = new FormData();
               fd.append('AttachmentId', attachment.attachmentid);
               fd.append('Customer', attachment.customer);
               fd.append('JobInv', attachment.jobInv);
               fd.append('JobName', attachment.jobName);
               fd.append('JobDwg', attachment.jobDwg);
               fd.append('Name', attachment.fileName);
               fd.append('Path', attachment.path);
               fd.append('attachedfile', attachment.attachedfile);

               return $http.post('/Streaming/Upload', fd, {
                   transformRequest: angular.identity,
                   headers: {
                       'Content-Type': undefined
                   }
               });
           };
       }]);
       myApp.controller('myCtrl', ['$scope', 'attachmentService', function ($scope, attachmentService) {
           $scope.uploadAttachment = function () {
               $scope.showUploadStatus = false;
               $scope.showUploadedData = false;

               var attachment = new Attachment("@customerid","@inv", " ", " ", $scope.attachedfile);

               attachmentService.uploadAttachment(attachment).then(function (response) { // success
                   if (response.status === 200) {
                       var inv = "@inv";
                       inv = inv.replace("&amp;", "%26");
                       var job = "@job";
                       job = job.replace("&amp;", "%26");
                       var dwg = "@dwg";
                       dwg = dwg.replace("&amp;", "%26");
                       window.location.href = "/Quote/Details/@ViewBag.customerId?quoteno=" + inv;
                   }
               },
                   function (response) { // failure
                       $scope.uploadStatus = "Attachment upload failed with status code: " + response.status;
                       $scope.showUploadStatus = true;
                       $scope.showUploadedData = false;
                       $scope.errors = [];
                       $scope.errors = parseErrors(response);
                   });
           };
       }]);

       function parseErrors(response) {
           var errors = [];
           for (var key in response.data) {
               for (var i = 0; i < response.data[key].length; i++) {
                   errors.push(key + ': ' + response.data[key][i]);
               }
           }
           return errors;
       }
</script>

Обновлен: Код на стороне сервера, как показано ниже:

[HttpPost]
[DisableFormValueModelBinding]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload()
{
    if (string.IsNullOrEmpty(userManager.GetUserName(User)))
        return RedirectToAction(actionName: "Login", controllerName: "Account");

    if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
    {
        return BadRequest($"Expected a multipart request, but got {Request.ContentType}");
    }

    // Used to accumulate all the form url encoded key value pairs in the 
    // request.
    var formAccumulator = new KeyValueAccumulator();
    string targetFilePath = Directory.GetCurrentDirectory() + "\\wwwroot\\Attachment";
    string fileName = "";
    var boundary = MultipartRequestHelper.GetBoundary(
        MediaTypeHeaderValue.Parse(Request.ContentType),
        _defaultFormOptions.MultipartBoundaryLengthLimit);
    var reader = new MultipartReader(boundary, HttpContext.Request.Body);

    var section = await reader.ReadNextSectionAsync();
    while (section != null)
    {
        ContentDispositionHeaderValue contentDisposition;
        var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);

        if (hasContentDispositionHeader)
        {
            if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
            {

                using (var targetStream = System.IO.File.Create(targetFilePath + fileName))
                {
                    await section.Body.CopyToAsync(targetStream);

                    _logger.LogInformation($"Copied the uploaded file '{targetFilePath + fileName}'");
                }
            }
            else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
            {
                // Content-Disposition: form-data; name="key"
                //
                // value

                // Do not limit the key name length here because the 
                // multipart headers length limit is already in effect.
                var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
                var encoding = GetEncoding(section);
                using (var streamReader = new StreamReader(
                    section.Body,
                    encoding,
                    detectEncodingFromByteOrderMarks: true,
                    bufferSize: 1024,
                    leaveOpen: true))
                {
                    // The value length limit is enforced by MultipartBodyLengthLimit
                    var value = await streamReader.ReadToEndAsync();
                    value = value.Replace("&amp;", "&");
                    if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
                    {
                        value = String.Empty;
                    }
                    formAccumulator.Append(key, value);

                    if (key.Equals("Path"))
                    {
                        targetFilePath += value;
                        Directory.CreateDirectory(targetFilePath);
                    }
                    if (key.Equals("Name"))
                        fileName = value;
                    if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit)
                    {
                        throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
                    }
                }
            }
        }

        // Drains any remaining section body that has not been consumed and
        // reads the headers for the next section.
        section = await reader.ReadNextSectionAsync();
    }

    // Bind form data to a model
    var attachment = new AttachFile();
    var formValueProvider = new FormValueProvider(
        BindingSource.Form,
        new FormCollection(formAccumulator.GetResults()),
        CultureInfo.CurrentCulture);

    var bindingSuccessful = await TryUpdateModelAsync(attachment, prefix: "",
        valueProvider: formValueProvider);
    if (!bindingSuccessful)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    }
    var user = userManager.GetUserName(User);
   // Add attachmnet to a jason file
   // ...
    var uploadedData = new UploadedData()
    {
        Invoice = attachment.JobInv,
        Name = attachment.JobName,
        Dwg = attachment.JobDwg,
        FileName = attachment.FileName,
        FilePath = targetFilePath,
        CreatedBy = user,
        CreatedDate = DateTime.Now
    };
    return Json(uploadedData);
}


public class AttachFile
{
    public int AttachmentId { get; set; }
    public string Customer { get; set; }
    public string JobInv { get; set; }
    public string JobName { get; set; }
    public string JobDwg { get; set; }

    public string FileName { get; set; }
    public string FilePath { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
}


public class UploadedData
{
    public string Invoice { get; set; }
    public string Name { get; set; }
    public string Dwg { get; set; }
    public string FileName { get; set; }
    public string FilePath { get; set; }
    public string Path { get; set; }
    public string CreatedBy { get; set; }
    public DateTime CreatedDate { get; set; }
}
...