如何使用nervgh的Angular-File-Upload发送formData

11

我正在使用 nervgh 的 Angular-File-Upload,地址为 https://github.com/nervgh/angular-file-upload

当我硬编码 preOpKey 时,它能正常工作。但我希望能够将 preOpKey 与文件一起发送,以便将文件保存到数据库中的相应记录。

angular-file-upload 在 API 中有一个 fileData,我在 $scope.OnPreinspectionSubmit() 中填充它,但出现问题的是:在我的 MVC 控制器中调用 SaveFile() 后无法找到该值。

我只需要知道如何将值与我的文件一起传递,并在我的 MVC 控制器中访问它。我想把它包含在 fileData 中也可以,但这并非回答我问题所必需。

这是我的 Angular 控制器:

var OperatorPreinspectionControllers = angular.module('OperatorPreinspectionControllers', ['angularFileUpload']);

OperatorPreinspectionControllers.controller('OperatorPreinspectionCtrl', ['$scope', '$http', 'FileUploader',
    function ($scope, $http, FileUploader) {

        $scope.uploader = new FileUploader({
            url: pageBaseUrl + 'image/SaveFile'
        });

        $scope.uploader.filters.push({
            name: 'imageFilter',
            fn: function (item /*{File|FileLikeObject}*/, options) {
                var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                return '|jpg|png|jpeg|bmp|gif|pdf|'.indexOf(type) !== -1;
            }
        });

        // Send the form data to the database
        $scope.OnPreinspectionSubmit = function () {
            if (confirm("Are you sure you want to save this information?")) {
                $http.post(pageBaseUrl + 'api/PreInspectionForm', $scope.formInformation).success(function (returnData) {
                    $scope.uploader.formData.push({ preOpKey: returnData });
                    $scope.uploader.uploadAll(); // Upload file
                });
            } else { }
        }
    }
]);

这是我的MVC控制器:

public void SaveFile()
    {
        HttpFileCollectionBase files = Request.Files;
        HttpPostedFileBase uploadedFile = files[0];

        var preOpKey = 123; // ???????

        // Turn the file into bytes
        byte[] data;
        using(Stream inputStream = uploadedFile.InputStream)
        {
            MemoryStream memoryStream = inputStream as MemoryStream;
            if(memoryStream == null)
            {
                memoryStream = new MemoryStream();
                inputStream.CopyTo(memoryStream);
            }
            data = memoryStream.ToArray();
        }

        PreOpManager.SaveImage(preOpKey, data, uploadedFile.FileName, uploadedFile.ContentType);
    }

谢谢您,

Aaron


我认为你可以通过长参数的POST数据发送密钥:$http({ url: 'request-url', method: "POST", data: { 'message' : message } }),然后只需在JSON POST数据上进行拾取并提交到数据库。 - jorblume
nervgh的Angular-File-Upload中一定有一个bug。我最后放弃使用该插件,改用danialfarid的Angular-File-Upload。这个插件有一个"formData"选项,只有这个可用。 :) - Aaron Salazar
哇,不幸啊。好吧,很高兴你把它都解决了。 - jorblume
我也在使用nervgh的Angular-File-Upload,并且在将文件传递给.NET MVC Web API控制器方面遇到了困难。 - Govind
1个回答

12

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接