如何在ASP .NET Web API 2应用程序中使用ng-file-upload保存文件?

时间:2016-07-25 21:00:10

标签: c# asp.net-web-api ng-file-upload

我尝试将文件保存到服务器,我使用 ng-file-upload 指令,我添加了下一个 html - 代码

<button class="button" ngf-select ng-model="fileCover" name="fileCover" ngf-pattern="'image/*'"
 ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100">Select</button>

 <button type="submit" ng-click="submitUpload(fileCover)">submit</button>

和我的 angularjs-code

 $scope.submitUpload = function (fileCover) {
    console.log(fileCover);
    Upload.upload({
        url: '/api/upload',
        data: { file: fileCover }
    });

};

我有一个空控制器:

  [Route("upload")]
    [HttpPost]
    public void Upload ( )
    {

    }

请告诉我,我如何在服务器端保存文件?感谢您的回答!

1 个答案:

答案 0 :(得分:2)

我有一个使用旧版ng-file-upload(angular-file-upload)的解决方案,我收到该文件的WebApi方法如下所示:

[HttpPost]
public async Task<HttpResponseMessage> Upload() {
    try {
        if (!Request.Content.IsMimeMultipartContent()) {
            Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = GetMultipartProvider();
        var result = await Request.Content.ReadAsMultipartAsync(provider);

        // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
        // so this is how you can get the original file name
        var originalFileName = GetDeserializedFileName(result.FileData.First());

        // uploadedFileInfo object will give you some additional stuff like file length,
        // creation time, directory name, a few filesystem methods etc..
        var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);

        // Create full path for where to move the uploaded file
        string targetFile = Path.Combine(uploadedFileInfo.DirectoryName, originalFileName);

        // If the file in the full path exists, delete it first otherwise FileInfo.MoveTo() will throw exception
        if (File.Exists(targetFile)) 
            File.Delete(targetFile);
        }

        // Move the uploaded file to the target folder
        uploadedFileInfo.MoveTo(targetFile);

        // targetFile now contains the uploaded file

        // Through the request response you can return an object to the Angular controller
        // You will be able to access this in the .success callback through its data attribute
        // If you want to send something to the .error callback, use the HttpStatusCode.BadRequest instead
        return new HttpResponseMessage(HttpStatusCode.OK);

    } catch (Exception ex) {
        return new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new ObjectContent(ex.GetType(), ex, new JsonMediaTypeFormatter()) };
    }
}

private MultipartFormDataStreamProvider GetMultipartProvider() {
    var uploadFolder = @"C:\Temp"

    if (Directory.Exists(uploadFolder) == false) Directory.CreateDirectory(uploadFolder);

    return new MultipartFormDataStreamProvider(uploadFolder);
}

private string GetDeserializedFileName(MultipartFileData fileData) {
    var fileName = GetFileName(fileData);
    return JsonConvert.DeserializeObject(fileName).ToString();
}

private string GetFileName(MultipartFileData fileData) {
    return fileData.Headers.ContentDisposition.FileName;
}

希望服务器端功能在我使用的和正在使用的版本之间的版本中没有太大变化。