1

I have a Task method that uploads images in my webapi project. Everything works fine but I would like to do the upload to my AWS cloud process in a separate task/thread, and then run some function after that process is complete. So to sum it up, here is what I am trying to complete.

  1. http request comes into API with a photo or video
  2. some validation stuff is done and then kicks off the new thread that starts the cloud upload
  3. End the 1st request with a 200 or some type of OK status

  4. While the first request has ended, a upload is in progress, and when that finish, run some sort of complete function on that. client does not need to be updated about with this function but some data needs to be saved.

Thanks for any help

    public async Task<HttpResponseMessage> PostMedia([FromUri]string userId, [FromUri]string eventId,[FromUri]string city,
            [FromUri]string title)
        {
            // Check if the request contains multipart/form-data. 
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            //temp directory
            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);
            try
            {
                var sb = new StringBuilder(); // Holds the response body 

                // Read the form data and return an async task. 
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the form data. 
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        sb.Append(string.Format("{0}: {1}\n", key, val));
                    }
                }

                // This illustrates how to get the file names for uploaded files. 
                foreach (var file in provider.FileData)
                {
//Needs to kick off new task/thread
                    using (
               var client = AWSClientFactory.CreateAmazonS3Client("key",
                                                                       "key"))
                    {
                        var fileInfo = new FileInfo(file.LocalFileName);
                        using (var stream = fileInfo.Open(FileMode.Open))
                        {
                            var request = new PutObjectRequest();
                            request.WithBucketName("Images")
                                   .WithCannedACL(S3CannedACL.PublicRead)
                                   .WithKey(ConfigurationManager.AppSettings["ImageBucket"] + fileInfo.Name +
                                   file.Headers.ContentDisposition.FileName.Substring(file.Headers.ContentDisposition.FileName.LastIndexOf('.')).Replace("\"", ""))
                                   .InputStream = stream;
                            client.PutObject(request);

                            sb.Append(string.Format("Uploaded file: {0} ({1} bytes)\n", fileInfo.Name, fileInfo.Length));
                            var mtype = MediaType.Picture;
                              if(file.Headers.ContentType.MediaType.StartsWith("image"))
                              {
                                  mtype = MediaType.Picture;
                              }
                              else if(file.Headers.ContentType.MediaType.StartsWith("video"))
                              {
                                  mtype = MediaType.Video;
                              }

                              if (File.Exists(fileInfo.FullName))
                              {
                                  File.Delete(fileInfo.FullName);
                              }
                        }
                    }
                }
                return new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.Created,
                    Content = new StringContent(sb.ToString())
                };
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
4

0 回答 0