Flask Upload Image to S3 without saving it to local file system The 2019 Stack Overflow Developer Survey Results Are InFlask: IOError when saving uploaded filesSlow Requests on Local Flask ServerUploading multiple files with FlaskRead file data without saving it in FlaskHow to serve static files in FlaskUploading and Downloading Image Files with FlaskFlask file upload is not saving the fileFlask upload file without saving itUpload file to S3 - Is it possible to pass the uploaded file object directly to boto3 without having to save the file in local server disk?flask upload CSV file without saving

Output the Arecibo Message

Cooking pasta in a water boiler

How to type a long/em dash `—`

Old scifi movie from the 50s or 60s with men in solid red uniforms who interrogate a spy from the past

The phrase "to the numbers born"?

Dropping list elements from nested list after evaluation

How did passengers keep warm on sail ships?

Will it cause any balance problems to have PCs level up and gain the benefits of a long rest mid-fight?

Is an up-to-date browser secure on an out-of-date OS?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

Relationship between Gromov-Witten and Taubes' Gromov invariant

I am an eight letter word. What am I?

Falsification in Math vs Science

APIPA and LAN Broadcast Domain

If a sorcerer casts the Banishment spell on a PC while in Avernus, does the PC return to their home plane?

Straighten subgroup lattice

What is this sharp, curved notch on my knife for?

What is the meaning of Triage in Cybersec world?

How to notate time signature switching consistently every measure

Why didn't the Event Horizon Telescope team mention Sagittarius A*?

Correct punctuation for showing a character's confusion

Can a flute soloist sit?

What do I do when my TA workload is more than expected?

Can there be female White Walkers?



Flask Upload Image to S3 without saving it to local file system



The 2019 Stack Overflow Developer Survey Results Are InFlask: IOError when saving uploaded filesSlow Requests on Local Flask ServerUploading multiple files with FlaskRead file data without saving it in FlaskHow to serve static files in FlaskUploading and Downloading Image Files with FlaskFlask file upload is not saving the fileFlask upload file without saving itUpload file to S3 - Is it possible to pass the uploaded file object directly to boto3 without having to save the file in local server disk?flask upload CSV file without saving



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I need to upload a a user submitted photo to an s3 bucket. However I keep getting the following error:



TypeError: expected str, bytes or os.PathLike object, not FileStorage


How am I able to store the file as string/bytes instead of FileStorage? The relevent code is as follows:



@user_api.route('upload-profile-photo', methods=['PUT'])
@Auth.auth_required
def upload_profile_photo():
"""
Upload User Profile Photo
"""
key = Auth.auth_user()
bucket = 'profile-photos'
content_type = request.mimetype
image_file = request.files['file']
client = boto3.client('s3',
region_name='sfo2',
endpoint_url='https://example.xxx.amazonaws.com',
aws_access_key_id=os.environ['ACCESS_KEY'],
aws_secret_access_key=os.environ['SECRET_KEY'])
with open(image_file, "rb") as f:
client.upload_fileobj(
bucket,
f,
key,
ExtraArgs='ACL': 'public-read', 'ContentType': content_type
)

return custom_response('message': 'image uploaded', 200)









share|improve this question




























    0















    I need to upload a a user submitted photo to an s3 bucket. However I keep getting the following error:



    TypeError: expected str, bytes or os.PathLike object, not FileStorage


    How am I able to store the file as string/bytes instead of FileStorage? The relevent code is as follows:



    @user_api.route('upload-profile-photo', methods=['PUT'])
    @Auth.auth_required
    def upload_profile_photo():
    """
    Upload User Profile Photo
    """
    key = Auth.auth_user()
    bucket = 'profile-photos'
    content_type = request.mimetype
    image_file = request.files['file']
    client = boto3.client('s3',
    region_name='sfo2',
    endpoint_url='https://example.xxx.amazonaws.com',
    aws_access_key_id=os.environ['ACCESS_KEY'],
    aws_secret_access_key=os.environ['SECRET_KEY'])
    with open(image_file, "rb") as f:
    client.upload_fileobj(
    bucket,
    f,
    key,
    ExtraArgs='ACL': 'public-read', 'ContentType': content_type
    )

    return custom_response('message': 'image uploaded', 200)









    share|improve this question
























      0












      0








      0








      I need to upload a a user submitted photo to an s3 bucket. However I keep getting the following error:



      TypeError: expected str, bytes or os.PathLike object, not FileStorage


      How am I able to store the file as string/bytes instead of FileStorage? The relevent code is as follows:



      @user_api.route('upload-profile-photo', methods=['PUT'])
      @Auth.auth_required
      def upload_profile_photo():
      """
      Upload User Profile Photo
      """
      key = Auth.auth_user()
      bucket = 'profile-photos'
      content_type = request.mimetype
      image_file = request.files['file']
      client = boto3.client('s3',
      region_name='sfo2',
      endpoint_url='https://example.xxx.amazonaws.com',
      aws_access_key_id=os.environ['ACCESS_KEY'],
      aws_secret_access_key=os.environ['SECRET_KEY'])
      with open(image_file, "rb") as f:
      client.upload_fileobj(
      bucket,
      f,
      key,
      ExtraArgs='ACL': 'public-read', 'ContentType': content_type
      )

      return custom_response('message': 'image uploaded', 200)









      share|improve this question














      I need to upload a a user submitted photo to an s3 bucket. However I keep getting the following error:



      TypeError: expected str, bytes or os.PathLike object, not FileStorage


      How am I able to store the file as string/bytes instead of FileStorage? The relevent code is as follows:



      @user_api.route('upload-profile-photo', methods=['PUT'])
      @Auth.auth_required
      def upload_profile_photo():
      """
      Upload User Profile Photo
      """
      key = Auth.auth_user()
      bucket = 'profile-photos'
      content_type = request.mimetype
      image_file = request.files['file']
      client = boto3.client('s3',
      region_name='sfo2',
      endpoint_url='https://example.xxx.amazonaws.com',
      aws_access_key_id=os.environ['ACCESS_KEY'],
      aws_secret_access_key=os.environ['SECRET_KEY'])
      with open(image_file, "rb") as f:
      client.upload_fileobj(
      bucket,
      f,
      key,
      ExtraArgs='ACL': 'public-read', 'ContentType': content_type
      )

      return custom_response('message': 'image uploaded', 200)






      flask boto3






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 4:35









      stack-flostack-flo

      971415




      971415






















          1 Answer
          1






          active

          oldest

          votes


















          1














          iTo achieve that with a FileStorage, I use the method put_object():



          from werkzeug import secure_filename

          @user_api.route('upload-profile-photo', methods=['PUT'])
          @Auth.auth_required
          def upload_profile_photo():
          """
          Upload User Profile Photo
          """
          key = Auth.auth_user()
          bucket = 'profile-photos'
          content_type = request.mimetype
          image_file = request.files['file']

          client = boto3.client('s3',
          region_name='sfo2',
          endpoint_url='https://example.xxx.amazonaws.com',
          aws_access_key_id=os.environ['ACCESS_KEY'],
          aws_secret_access_key=os.environ['SECRET_KEY'])

          filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename

          client.put_object(Body=image_file,
          Bucket=bucket,
          Key=filename,
          ContentType=content_type)

          return custom_response('message': 'image uploaded', 200)



          Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename.
          Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).



          I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()






          share|improve this answer

























          • I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

            – stack-flo
            Mar 22 at 15:57











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292986%2fflask-upload-image-to-s3-without-saving-it-to-local-file-system%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          iTo achieve that with a FileStorage, I use the method put_object():



          from werkzeug import secure_filename

          @user_api.route('upload-profile-photo', methods=['PUT'])
          @Auth.auth_required
          def upload_profile_photo():
          """
          Upload User Profile Photo
          """
          key = Auth.auth_user()
          bucket = 'profile-photos'
          content_type = request.mimetype
          image_file = request.files['file']

          client = boto3.client('s3',
          region_name='sfo2',
          endpoint_url='https://example.xxx.amazonaws.com',
          aws_access_key_id=os.environ['ACCESS_KEY'],
          aws_secret_access_key=os.environ['SECRET_KEY'])

          filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename

          client.put_object(Body=image_file,
          Bucket=bucket,
          Key=filename,
          ContentType=content_type)

          return custom_response('message': 'image uploaded', 200)



          Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename.
          Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).



          I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()






          share|improve this answer

























          • I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

            – stack-flo
            Mar 22 at 15:57















          1














          iTo achieve that with a FileStorage, I use the method put_object():



          from werkzeug import secure_filename

          @user_api.route('upload-profile-photo', methods=['PUT'])
          @Auth.auth_required
          def upload_profile_photo():
          """
          Upload User Profile Photo
          """
          key = Auth.auth_user()
          bucket = 'profile-photos'
          content_type = request.mimetype
          image_file = request.files['file']

          client = boto3.client('s3',
          region_name='sfo2',
          endpoint_url='https://example.xxx.amazonaws.com',
          aws_access_key_id=os.environ['ACCESS_KEY'],
          aws_secret_access_key=os.environ['SECRET_KEY'])

          filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename

          client.put_object(Body=image_file,
          Bucket=bucket,
          Key=filename,
          ContentType=content_type)

          return custom_response('message': 'image uploaded', 200)



          Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename.
          Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).



          I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()






          share|improve this answer

























          • I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

            – stack-flo
            Mar 22 at 15:57













          1












          1








          1







          iTo achieve that with a FileStorage, I use the method put_object():



          from werkzeug import secure_filename

          @user_api.route('upload-profile-photo', methods=['PUT'])
          @Auth.auth_required
          def upload_profile_photo():
          """
          Upload User Profile Photo
          """
          key = Auth.auth_user()
          bucket = 'profile-photos'
          content_type = request.mimetype
          image_file = request.files['file']

          client = boto3.client('s3',
          region_name='sfo2',
          endpoint_url='https://example.xxx.amazonaws.com',
          aws_access_key_id=os.environ['ACCESS_KEY'],
          aws_secret_access_key=os.environ['SECRET_KEY'])

          filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename

          client.put_object(Body=image_file,
          Bucket=bucket,
          Key=filename,
          ContentType=content_type)

          return custom_response('message': 'image uploaded', 200)



          Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename.
          Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).



          I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()






          share|improve this answer















          iTo achieve that with a FileStorage, I use the method put_object():



          from werkzeug import secure_filename

          @user_api.route('upload-profile-photo', methods=['PUT'])
          @Auth.auth_required
          def upload_profile_photo():
          """
          Upload User Profile Photo
          """
          key = Auth.auth_user()
          bucket = 'profile-photos'
          content_type = request.mimetype
          image_file = request.files['file']

          client = boto3.client('s3',
          region_name='sfo2',
          endpoint_url='https://example.xxx.amazonaws.com',
          aws_access_key_id=os.environ['ACCESS_KEY'],
          aws_secret_access_key=os.environ['SECRET_KEY'])

          filename = secure_filename(file.filename) # This is convenient to validate your filename, otherwise just use file.filename

          client.put_object(Body=image_file,
          Bucket=bucket,
          Key=filename,
          ContentType=content_type)

          return custom_response('message': 'image uploaded', 200)



          Note the call to secure_filename() is optional (you can simply pass image_file.filename), but can be very handy to validate the filename.
          Otherwise it would be nice to add some exception handlings, but the rough idea is here: no need to open() the file (that would need to be stored locally).



          I encourage to have a look at the documentation here, to understand the difference with upload_fileobj()







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 22 at 5:50

























          answered Mar 22 at 5:31









          CloCCloC

          755521




          755521












          • I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

            – stack-flo
            Mar 22 at 15:57

















          • I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

            – stack-flo
            Mar 22 at 15:57
















          I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

          – stack-flo
          Mar 22 at 15:57





          I guess I misunderstood the functions put.object and upload_fileobj. Your suggestion worked. Thanks!

          – stack-flo
          Mar 22 at 15:57



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55292986%2fflask-upload-image-to-s3-without-saving-it-to-local-file-system%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현