如何在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')toimageFile.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
dataparameter torequests.post()that passes theFNAMEkey 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_filenamewithdfile.name
How It Works:
- The client sends both the image file and the desired filename in a single POST request
- The server parses both pieces of data
- The server saves the image using the exact filename provided by the client
内容的提问来源于stack exchange,提问作者user19728274
相关产品推荐
相关产品推荐

