如何使用formdata将observableArray传递给控制器​​?

时间:2014-07-21 13:37:19

标签: jquery asp.net-mvc json file-upload knockout.js

当我在浏览后点击上传文件后我得到了一个上传控件我需要将该文件发送到控制器并且我需要另外向正常控制器发送一个ObservableArray(其中包含相关数据)。

我很无知如何处理这些东西累了很多东西而且我最终没什么好酷的。

我的上传按钮上的Viewmodel代码点击:

self.FFAttach = function () {
                    var formdata = new FormData(); //FormData object
                    var fileInput = document.getElementById('FFtoSP');

                    ////Iterating through each files selected in fileInput

                    for (i = 0; i < fileInput.files.length; i++) {
                        //Appending each file to FormData object
                        formdata.append(fileInput.files[i].name, fileInput.files[i]);
                    }

                    //Creating an XMLHttpRequest and sending
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '/WorkCompletion/Upload/');

                    xhr.send(formdata);

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 4 && xhr.status == 200) {

                            path = xhr.responseText;
                            alert(xhr.responseText);
                        }
                    }
}

我的控制器代码:

  [HttpPost]
public ActionResult Upload(string id)
{

    string uploadedPath = string.Empty;
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file

        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = Path.GetFileName(file.FileName);
        fileName = "Contract" + "_" + "CreateContract" + "_" + fileName;
        string mimeType = file.ContentType;
        var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);



        //To save file, use SaveAs method
        file.SaveAs(path); //File will be saved in application root


        byte[] fileData = null;
        using (var binaryReader = new BinaryReader(file.InputStream)) { fileData = binaryReader.ReadBytes(file.ContentLength); }
        uploadedPath = UploadToSharepoint(path, id, fileName, file, fileData); 


    }
    return Json(uploadedPath);

}

如果我想发送一个文件并进一步保存,上面的代码工作正常,但当我尝试发送一个obeservable数组时,没有任何事情发生。

我尝试过将oberservable作为参数传递,是的,它不会按预期工作,并尝试附加formdata.append("myparam", ko.toJS(self.AttachmentUsableArray()));当我保留这段代码时,控制器中的调试器甚至可能会发生悲伤。

链接我一直在推荐您可能会找到方便:

Webapi ajax formdata upload with extra parameters

File upload Jquery WebApi

任何想法都表示赞赏。

0 个答案:

没有答案