Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Trying to read ContentDisposition
Message
 
 
À
Tous
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Titre:
Trying to read ContentDisposition
Versions des environnements
Environment:
C# 5.0
OS:
Windows 10
Database:
MS SQL Server
Divers
Thread ID:
01633696
Message ID:
01633696
Vues:
54
Hi everybody,

My colleague is working on the following problem and I'm trying to help. We switched from AngularJS 1.3 to 1.5 and some things have changed, in particular file-uploader. This is our latest attempt to pass the file along with some additional info and it's according to the documentation.

This is our js file code:
$scope.upload = Upload.upload({
                                url: $scope.uploadOptions.url, //upload.php script, node.js route, or servlet url
                                method: 'POST', // or 'PUT',
                                headers: {'header-key': 'header-value'},
                                //withCredentials: true,
                                data: { file: file, info: $scope.uploadOptions.options },
                                
                                //data: { key: file, otherInfo: {id: 1, person: 'Naomi'}}
                                //file: file
                                //file: file // or list of files ($files) for html5 only
                                //fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...] // to modify the name of the file(s)
                                // customize file formData name ('Content-Disposition'), server side file variable name. 
                                //fileFormDataName: myFile, //or a list of names for multiple files (html5). Default is 'file' 
                                // customize how data is added to formData. See #40#issuecomment-28612000 for sample code
                                //formDataAppender: function(formData, key, val){}
                            }).progress(function (evt) {
                                //console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));

                            }).success(function (data, status, headers, config) {
                                //$scope.filesLoading -= data.length;
                                $scope.filesLoading = 0;
                                if (data[0] && data[0].key && data[0].key.length > 0) {
                                    //find the file data and update it
                                    $.each($scope.arFileInfo, function (index, fileInfo) {
                                        if (fileInfo.fileData.name == config._file.name) {
                                            fileInfo.key = data[0].key;
                                            return false;
                                        };
                                    });
                                };
                                $scope.uploadOptions.onSuccess(data);
                            }).error(function (data, status, headers, config) {
                                if ($scope.uploadOptions.onError) {
                                    $scope.uploadOptions.onError(status);
                                }
                                else
                                    $scope.errorMessage = resourceFactory.getResource('Messages', 'errorUploadingFile');
                            });
                        };

                    }
and this is our API code
        [HttpPost]
        // POST api/User/Image
        [Route("UploadImage")]
        public async Task<HttpResponseMessage> PostContactImages()
        {
            // Check if the request contains multipart/form-data.
            if (Request.Content.IsMimeMultipartContent("form-data"))
            {
                //var FormData = await Request.Content.ReadAsFormDataAsync();
                try
                {
                    //get the image options
                    var strImageOptions = HttpContext.Current.Request.Form["data"];

                    //HttpFileCollection files = HttpContext.Current.Request.Files;
                    //for (int i = 0; i < files.Count; i++)
                    //{
                    //    HttpPostedFile file = files[i];
                    //    string fname = @"D:\Development\Main\SysManager\SysManager.Web\ApiControllers\Uploads\STAN\" + file.FileName;
                    //    file.SaveAs(fname);
                    //}
                    
                    //var imageOptions = Newtonsoft.Json.JsonConvert.DeserializeObject<ContactPhotoOptionsViewModel>(strImageOptions);

                    //var provider = GetMultipartProvider();
                    //var result = await Request.Content.ReadAsMultipartAsync(provider);
                    //var strImageOptions = GetFormData<ContactPhotoOptionsViewModel>(result);

                    var resultOut = new List<ImageUploadResult>();

                    var streamProvider = new MultipartMemoryStreamProvider();
                    streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);

                    foreach (var item in streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName)))
                    {
                        using (Stream stPictureSource = new MemoryStream(await item.ReadAsByteArrayAsync()))
                        {
                            byte[] imageBytes;

                            //if (imageOptions.MaxWidth > 0 || imageOptions.MaxHeight > 0) //scale the image
                            //{
                            //    Image im = Bitmap.FromStream(stPictureSource);
                            //    var newSize = ImageUtilities.GetScaledSize(im, imageOptions.MaxWidth, imageOptions.MaxHeight);
                            //    imageBytes = ImageUtilities.ScaleToSize(im, newSize, System.Drawing.Imaging.ImageFormat.Jpeg);

                            //}
                            //else  //just save it
                            //{
                            //    imageBytes = new Byte[stPictureSource.Length];
                            //    stPictureSource.Read(imageBytes, 0, Convert.ToInt32(stPictureSource.Length));
                            //}
                            imageBytes = new Byte[stPictureSource.Length];
                            stPictureSource.Read(imageBytes, 0, Convert.ToInt32(stPictureSource.Length));
                            var contactImages = new ContactPhotos();
                            contactImages.Photo = imageBytes;
                            _contactPhotosAdapter.Add(contactImages);
                            var vm = AutoMapperConfig.Mapper.Map<ContactPhotos, ContactPhotosViewModel>(contactImages);

                            resultOut.Add(new ImageUploadResult() { FileName = "Photo", DataObject = vm, Key = vm.PhotoId.ToString() });
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, resultOut.ToArray());
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.ToString());
                    return Request.CreateResponse(HttpStatusCode.BadRequest);
                }
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
The first variable is always null. So, we're right now down to this info:

HttpContext.Current.Request.Form

and the value in the immediate window reads as
{info%5bimageOptions%5d%5bmaxWidth%5d=200&info%5bimageOptions%5d%5bmaxHeight%5d=0&info%5bimageOptions%5d%5bcreateThumb%5d=false&info%5bimageOptions%5d%5bthumbWidth%5d=0&info%5bimageOptions%5d%5bthumbHeight%5d=0&info%5bimageOptions%5d%5bimageFormat%5d=jpeg}
But we can not figure out how to get that info or imageOptions into actual object. We tried all variations we can think of

HttpContext.Current.Request.Form["info"]

and some other things, but it comes null every time.

We're very close, just need figuring out last piece to get it.
If it's not broken, fix it until it is.


My Blog
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform