简体   繁体   中英

Unable send excel file data to web api

In my angular app , I am trying to upload an excel file to web api from Angular JS but I am unable to do so . The method in the server web api is not being hit.

The angular code looks like :

    $scope.file = null;

    //UPLOAD FILE CODE
    var formdata;
    $scope.getTheFiles = function ($files) {
        console.log($files[0].type);
        formdata = new FormData();
        angular.forEach($files, function (value, key) {
            formdata.append(key, value);
        });
    };

    // NOW UPLOAD THE FILES.
    $scope.uploadFiles = function () {
        var request = {
            method: 'POST',
            url: BasePath + 'uploadNative/UploadFiles/',
            data: formdata,
            headers: {
                'Content-Type': undefined
            }
        };

        // SEND THE FILES.
        console.log(formdata);

        if (formdata != null || formdata != undefined) {
            $http(request)
                .success(function (response) {
                    if (response != "Failed!") {
                        console.log("Succeeds");
                    }
                    else {
                        console.log("Failed");
                    }
                })
                .error(function () {
                });
        }

And the UI MVC controller which should invoke the web api controller causes exception.

    public async Task<JsonResult> UploadFiles()
    {
        System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

        string url = BaseURL + "api/Upload/groupmembershipupload/";
        string res = await Models.Resource.PostFileAsync(url, Token, hfc, ClientID);
        var result = (new JavaScriptSerializer()).DeserializeObject(res);
        return Json(result);
    }

This PostFileAsync fires the exception.

            using (client = new HttpClient())
            {

                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("multipart/form-data"));
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + oauthToken);
                client.DefaultRequestHeaders.Add("ClientID", ClientID);
                var content = new MultipartFormDataContent();
                System.Web.HttpPostedFile hpf = data[0];


                byte[] fileData = null;
                using (var sds = new BinaryReader(hpf.InputStream))
                {
                    fileData = sds.ReadBytes(hpf.ContentLength);
                }
                content.Add(new ByteArrayContent(fileData, 0, fileData.Count()));
                //using (response = await client.PostAsJsonAsync(url + "?=" + DateTime.Now.Ticks, data))
                using (response = await client.PostAsync(url + "?=" + DateTime.Now.Ticks, content))
                {

...the response is Http Error 415 "Unsupported Media Type". It does not call the service.

Change the headers to:

headers: {
            'Content-Type': 'multipart/form-data'
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM