mercredi 24 juin 2020

How to send image file along with other parameter in asp.net c#?

I want to send image file to sql server using c#. the below code is working and saving file in folder and path in database but I want the same data in Api response.I've my custom response class RegistrationResponse. I'm begginner in this so I'm very stuck out of this and your help will be highly appreciated

public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
        {
            object data = "";
            NameValueCollection col = HttpContext.Current.Request.Form;        

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = HttpContext.Current.Server.MapPath("~/images");
            var provider = new MultipartFormDataStreamProvider(root);
            

            // Read the form data and return an async task.
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }
                        //read file data
                        foreach (MultipartFileData dataItem in provider.FileData)
                    {
                        try
                        {
                            string description = string.Empty;
                            string userId = string.Empty;
                            String fileName = string.Empty;

                                // Show all the key-value pairs.
                                foreach (var key in provider.FormData.AllKeys)
                            {
                                foreach (var val in provider.FormData.GetValues(key))
                                {

                                    if (key.ToString().ToLower() == "userid")
                                    {
                                        userId = val;
                                    }
                                    else if (key.ToString().ToLower() == "description")
                                    {
                                        description = val;
                                    }

                                }
                            }

                            String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
                            fileName = userId + Path.GetExtension(name);
                            File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));

                            using (var db = new AlumniDBEntities())
                            {
                                //saving path and data in database table
                                Post userPost = new Post();
                                userPost.Files = fileName;
                                userPost.Description = description;
                                userPost.UserID = Convert.ToInt32(userId);
                                userPost.CreatedDate = DateTime.Now;

                                db.Posts.Add(userPost);
                                db.SaveChanges();
                               
                                data = db.Posts.Where(x => x.PostID == 
                                userPost.PostID).FirstOrDefault();
                                string output = JsonConvert.SerializeObject(data);                               
                            }
                        }
                        catch (Exception ex)
                        {
                            return Request.CreateResponse(ex);
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.Created);                  
                });

            var response = new RegistrationResponse
            {
                success = true,
                status = HttpStatusCode.OK,
                message = "Success",
                data = data
            };
            return response;
        }
    }



Aucun commentaire:

Enregistrer un commentaire