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

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript