Лямбда-функция AWS в .NET выдает ошибку при создании нового файла для корзины s3 (невозможно определить длину содержимого) - PullRequest
0 голосов
/ 24 мая 2018

Я занимаюсь разработкой лямбда-функции AWS с использованием ядра .NET 2. Это моя первая разработка лямбда-функции AWS с использованием .NET.То, что я пытаюсь сделать сейчас, так просто, прочитайте существующий файл и сохраните файл с новым именем (новым именем).Чтение файла работает нормально.Но когда я сохраняю файл с помощью PutObjectRequest, он выдает ошибку.

Это мой код для функции обработчика

public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
      {
         var s3Event = evnt.Records?[0].S3;
         if(s3Event == null)
         {
            return null;
         }

         try
         {
            if(s3Event.Object.Key.ToLower().Contains("thumb"))
            {
               //Console.WriteLine("The image is already a thumb file");
               return "The file is aready a thumb image file";
            }

            string[] pathSegments = s3Event.Object.Key.Split('/');
            string eventCode = pathSegments[0];
            string userEmail = pathSegments[1];
            string filename = pathSegments[2];
            string extension = Path.GetExtension(filename); //.jpeg with "dot"
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename);

            using(var objectResponse = await this.S3Client.GetObjectAsync(s3Event.Bucket.Name, s3Event.Object.Key))
            {
               using(Stream responseStream = objectResponse.ResponseStream)
               {
                  //This code is throwing error
                  await this.S3Client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
                  {
                     BucketName = s3Event.Bucket.Name,
                     Key = fileNameWithoutExtension + ".thumb" + extension,
                     InputStream = responseStream
                  });
               }
            }

            return "Thumbnail version of the image has been created";

         }
         catch(Exception e)
         {
            context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
            context.Logger.LogLine(e.Message);
            context.Logger.LogLine(e.StackTrace);
            throw;
         }
      }

Когда я запускаю тестовую функцию, она выдает мне эту ошибку.

{
  "errorType": "AggregateException",
  "errorMessage": "One or more errors occurred. (Could not determine content length)",
  "stackTrace": [
    "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
    "at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
  ],
  "cause": {
    "errorType": "AmazonS3Exception",
    "errorMessage": "Could not determine content length",
    "stackTrace": [
      "at Amazon.S3.Model.Internal.MarshallTransformations.PutObjectRequestMarshaller.GetStreamWithLength(Stream baseStream, Int64 hintLength)",
      "at Amazon.S3.Model.Internal.MarshallTransformations.PutObjectRequestMarshaller.Marshall(PutObjectRequest putObjectRequest)",
      "at Amazon.Runtime.Internal.Marshaller.PreInvoke(IExecutionContext executionContext)",
      "at Amazon.Runtime.Internal.Marshaller.InvokeAsync[T](IExecutionContext executionContext)",
      "at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()",
      "--- End of stack trace from previous location where exception was thrown ---",
      "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
      "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
      "at Amazon.S3.Internal.AmazonS3ExceptionHandler.<InvokeAsync>d__1`1.MoveNext()",
      "--- End of stack trace from previous location where exception was thrown ---",
      "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
      "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
      "at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__5`1.MoveNext()",
      "--- End of stack trace from previous location where exception was thrown ---",
      "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
      "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
      "at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__1`1.MoveNext()",
      "--- End of stack trace from previous location where exception was thrown ---",
      "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
      "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
      "at AwsS3Lambda.Function.<FunctionHandler>d__10.MoveNext() in C:\\Users\\Acer\\Desktop\\MementoCSharp\\memento-dotnet\\AwsS3Lambda\\Function.cs:line 99"
    ]
  },
  "causes": [
    {
      "errorType": "AmazonS3Exception",
      "errorMessage": "Could not determine content length",
      "stackTrace": [
        "at Amazon.S3.Model.Internal.MarshallTransformations.PutObjectRequestMarshaller.GetStreamWithLength(Stream baseStream, Int64 hintLength)",
        "at Amazon.S3.Model.Internal.MarshallTransformations.PutObjectRequestMarshaller.Marshall(PutObjectRequest putObjectRequest)",
        "at Amazon.Runtime.Internal.Marshaller.PreInvoke(IExecutionContext executionContext)",
        "at Amazon.Runtime.Internal.Marshaller.InvokeAsync[T](IExecutionContext executionContext)",
        "at Amazon.Runtime.Internal.CallbackHandler.<InvokeAsync>d__9`1.MoveNext()",
        "--- End of stack trace from previous location where exception was thrown ---",
        "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
        "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
        "at Amazon.S3.Internal.AmazonS3ExceptionHandler.<InvokeAsync>d__1`1.MoveNext()",
        "--- End of stack trace from previous location where exception was thrown ---",
        "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
        "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
        "at Amazon.Runtime.Internal.ErrorCallbackHandler.<InvokeAsync>d__5`1.MoveNext()",
        "--- End of stack trace from previous location where exception was thrown ---",
        "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
        "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
        "at Amazon.Runtime.Internal.MetricsHandler.<InvokeAsync>d__1`1.MoveNext()",
        "--- End of stack trace from previous location where exception was thrown ---",
        "at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()",
        "at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)",
        "at AwsS3Lambda.Function.<FunctionHandler>d__10.MoveNext() in C:\\Users\\Acer\\Desktop\\MementoCSharp\\memento-dotnet\\AwsS3Lambda\\Function.cs:line 99"
      ]
    }
  ]
}

Что не так икак я могу решить это?Как я могу сохранить новый файл?

1 Ответ

0 голосов
/ 24 мая 2018

Я бы изменил:

await this.S3Client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
{
    BucketName = s3Event.Bucket.Name,
    Key = fileNameWithoutExtension + ".thumb" + extension,
    InputStream = responseStream
});

на:

await this.S3Client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
{
    BucketName = s3Event.Bucket.Name,
    Key = fileNameWithoutExtension + ".thumb" + extension,
    InputStream = responseStream,
    Headers.ContentLength = s3event.object.size
});

Это говорит S3, насколько велик объект, который вы храните.Когда вы получите действительный код миниатюры, вместо Headers.ContentLength будет использоваться длина миниатюры.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...