3

我有以下代码片段,用于通过 Ajax 帖子上传文件(使用 Knockout js 库)

ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
    $(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

    var options = ko.utils.unwrapObservable(valueAccessor()),
        property = ko.utils.unwrapObservable(options.property),
        url = ko.utils.unwrapObservable(options.url);

    if (property && url) {

        $(element).change(function () {
            if (element.files.length) {
                var $this = $(this),
                    fileName = $this.val();
                alert(fileName);
                // this uses jquery.form.js plugin
                $(element.form).ajaxSubmit({
                    url: url, //WEB API URL
                    type: "POST",
                    dataType: "text", //I want to upload .doc / excell files
                    headers: { "Content-Disposition": "attachment; filename=" + fileName },
                    beforeSubmit: function () {
                        $(".progress").show();
                        $(".progressError").hide();
                        $(".bar").width("0%")
                        $(".percent").html("0%");
                    },
                    uploadProgress: function (event, position, total, percentComplete) {
                        var percentVal = percentComplete + "%";
                        $(".bar").width(percentVal)
                        $(".percent").html(percentVal);
                    },
                    success: function (data) {
                        $(".progress").hide();
                        $(".progressError").hide();
                        // set viewModel property to filename
                        bindingContext.$data[property](data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $(".progress").hide();
                        $("div.progressError").html(jqXHR.responseText);
                    }
                });
            }
        });
    }
}

}

现在我的问题是为此创建 WEB API。

$(element.form).ajaxSubmit({
    url: url, //WEB API URL
    type: "POST",
    dataType: "text", //I want to upload .doc / excell files
    headers: { "Content-Disposition": "attachment; filename=" + fileName },

我想上传 Word/Excel 文档。有人可以告诉我如何在 ASP.NET WEB API 中完成这项工作吗?

更新:

我终于为此做了一个WEB API

  public class UploadController : ApiController
{

    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);
        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);

            //return new HttpResponseMessage()
            //{
            //    Content = new StringContent("File uploaded.")
            //};

        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

它工作正常(数据成功上传)但问题是,数据成功上传后似乎没有点击此部分。

  success: function (data) {
                        $(".progress").hide();
                        $(".progressError").hide();
                        // set viewModel property to filename
                        bindingContext.$data[property](data);
                    },

我必须通知客户上传的状态。

4

0 回答 0