title: How to upload File in FastAPI, then to Amazon S3 and finally process it?
body: <p>I have a FastAPI endpoint that receives a file, uploads it to s3, and then processes it. Everything works fine except for the processing, that fails with this message:</p>
  <pre class="lang-txt prettyprint-override"><code>  File &quot;/usr/local/lib/python3.9/site-packages/starlette/datastructures.py&quot;, line 441, in read
      return self.file.read(size)
    File &quot;/usr/local/lib/python3.9/tempfile.py&quot;, line 735, in read
      return self._file.read(*args)
  ValueError: I/O operation on closed file.
  </code></pre>
  <p>My simplified code looks like this:</p>
  <pre class="lang-python prettyprint-override"><code>async def process(file: UploadFile):
      reader = csv.reader(iterdecode(file.file.read(), &quot;utf-8&quot;), dialect=&quot;excel&quot;)  # This fails!
      datarows = []
      for row in reader:
          datarows.append(row)
      return datarows
  </code></pre>
  <p>How can I read the contents of the uploaded file?</p>
  <p><strong>UPDATE</strong></p>
  <p>I managed to isolate the problem a bit more. Here's my simplified endpoint:</p>
  <pre class="lang-python prettyprint-override"><code>import boto3
  from loguru import logger
  from botocore.exceptions import ClientError
  
  
  UPLOAD = True
  
  @router.post(&quot;/&quot;)
  async def upload(file: UploadFile = File(...)):
      if UPLOAD:
          # Upload the file
          s3_client = boto3.client(&quot;s3&quot;, endpoint_url=&quot;http://localstack:4566&quot;)
          try:
              s3_client.upload_fileobj(file.file, &quot;local&quot;, &quot;myfile.txt&quot;)
          except ClientError as e:
              logger.error(e)
      contents = await file.read()
      return JSONResponse({&quot;message&quot;: &quot;Success!&quot;})
  </code></pre>
  <p>If <code>UPLOAD</code> is True, I get the error. If it's not, everything works fine. It seems boto3 is closing the file after uploading it. Is there any way I can reopen the file? Or send a copy to <code>upload_fileobj</code>?</p>