You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flask图片上传API中接收客户端传递的文件名并以此保存图片

Solution: Save Image with Client-Specified Filename

Let's tweak your code so the server saves the uploaded image using the filename the client sends over. Here's the step-by-step fix for both your server and client scripts:

Modified Server Code (server.py)

We'll enable the commented-out logic to receive the filename parameter and use it when saving the image:

from flask import Flask
from flask_restful import Resource, Api, reqparse
import werkzeug

app = Flask(__name__)
api = Api(app)

class UploadImage(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        # Add argument to accept the filename from the client
        parser.add_argument('FNAME', required=True)
        parser.add_argument('file', type=werkzeug.datastructures.FileStorage, location='files')
        args = parser.parse_args()
        imageFile = args['file']
        # Fetch the client-specified filename
        filename = args['FNAME']
        print(f"Received filename to save: {filename}")
        # Save the image using the provided filename instead of hardcoding
        imageFile.save(filename)
        return {"status": "success", "saved_as": filename}

api.add_resource(UploadImage, '/uploadimage')

if __name__ == '__main__':
    from waitress import serve
    print("Running....")
    serve(app,host="0.0.0.0",port=8080)
    print("Stopped....")

Key Updates:

  • Uncommented parser.add_argument('FNAME', required=True) to capture the filename parameter from the client
  • Retrieved the client's desired filename with filename = args['FNAME']
  • Changed imageFile.save('test.jpg') to imageFile.save(filename) to use the custom name
  • Added a JSON response to confirm the image was saved with the correct name (helpful for debugging)

Modified Client Code (client.py)

We'll add a data parameter to the POST request to send your desired filename to the server:

import requests

# Open your local image file
dfile = open("test.jpg", "rb")
url = "http://127.0.0.1:8080/uploadimage"

# Set the filename you want the server to use for the saved image
desired_filename = "my_custom_photo.jpg"

# Send both the image file and the filename parameter
test_res = requests.post(url, files={"file": dfile}, data={"FNAME": desired_filename})
print(test_res.json())  # Print the server's confirmation response

if test_res.ok:
    print(" File uploaded successfully ! ")
else:
    print(" Please Upload again ! ")

Key Updates:

  • Added a data parameter to requests.post() that passes the FNAME key with your custom filename
  • Updated the print statement to show the server's JSON response (so you can verify the saved filename)
  • If you want to use the original name of your local file, replace desired_filename with dfile.name

How It Works:

  1. The client sends both the image file and the desired filename in a single POST request
  2. The server parses both pieces of data
  3. The server saves the image using the exact filename provided by the client

内容的提问来源于stack exchange,提问作者user19728274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 16:47:40