Using curl to upload POST data with files

本文介绍如何使用cURL工具进行HTTP POST操作,不仅发送数据参数,还上传指定名称的文件。通过调整cURL命令,确保PHP端能正确接收文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://stackoverflow.com/questions/12667797/using-curl-to-upload-post-data-with-files

************************************************************************
I would like to use cURL to not only send data parameters in HTTP POST but to also upload files with specific form name. How should I go about doing that ?

HTTP Post parameters:

userid = 12345 filecomment = This is an image file

HTTP File upload: File location = /home/user1/Desktop/test.jpg Form name for file = image (correspond to the $_FILES['image'] at the PHP side)

I figured part of the cURL command as follows:


curl -d "userid=1&filecomment=This is an image file" --data-binary @"/home/user1/Desktop/test.jpg" localhost/uploader.php

The problem I am getting is as follows:

Notice: Undefined index: image in /var/www/uploader.php

The problem is I am using $_FILES['image'] to pick up files in the PHP script.

How do I adjust my cURL commands accordingly ?

=====================

You need to use the -F option:
-F/--form <name=content> Specify HTTP multipart POST data (H)

try this.

curl \
  -F "userid=1" \
  -F "filecomment=This is an image file" \
  -F "image=@/home/user1/Desktop/test.jpg" \
  localhost/uploader.php

=========================

Catching the user id as path variable (recommended):

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "data=@test.mp3" http://mysuperserver/media/1234/upload/
Catching the user id as part of the form:

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "data=@test.mp3;userid=1234" http://mysuperserver/media/upload/

==================

....................................


import os import json import time import requests base_url = "http://127.0.0.1:1224" url = "{}/api/doc/upload".format(base_url) print("=======================================") print("===== 1. Upload file, get task ID =====") print("== URL:", url) # File to be recognized file_path = r"/home/ubuntu/桌面/起诉意见书.pdf" # Task parameters options_json = json.dumps( { "doc.extractionMode": "mixed", } ) with open(file_path, "rb") as file: response = requests.post(url, files={"file": file}, data={"json": options_json}) response.raise_for_status() res_data = json.loads(response.text) if res_data["code"] == 101: # If code == 101, it indicates that the server did not receive the uploaded file. # On some Linux systems, if file_name contains non-ASCII characters, this error might occur. # In this case, we can specify a temp_name containing only ASCII characters to construct the upload request. file_name = os.path.basename(file_path) file_prefix, file_suffix = os.path.splitext(file_name) temp_name = "temp" + file_suffix print("[Warning] Detected file upload failure: code == 101") print( "Attempting to use temp_name", temp_name, "instead of the original file_name", file_name, ) with open(file_path, "rb") as file: response = requests.post( url, # use temp_name to construct the upload request files={"file": (temp_name, file)}, data={"json": options_json}, ) response.raise_for_status() res_data = json.loads(response.text) assert res_data["code"] == 100, "Task submission failed: {}".format(res_data) id = res_data["data"] print("Task ID:", id) url = "{}/api/doc/result".format(base_url) print("===================================================") print("===== 2. Poll task status until OCR task ends =====") print("== URL:", url) headers = {"Content-Type": "application/json"} data_str = json.dumps( { "id": id, "is_data": True, "format": "text", "is_unread": True, } ) while True: time.sleep(1) response = requests.post(url, data=data_str, headers=headers) response.raise_for_status() res_data = json.loads(response.text) assert res_data["code"] == 100, "Failed to get task status: {}".format(res_data) print( " Progress: {}/{}".format( res_data["processed_count"], res_data["pages_count"] ) ) if res_data["data"]: print("{}\n========================".format(res_data["data"])) if res_data["is_done"]: state = res_data["state"] assert state == "success", "Task execution failed: {}".format( res_data["message"] ) print("OCR task completed.") break url = "{}/api/doc/download".format(base_url) print("======================================================") print("===== 3. Generate target file, get download link =====") print("== URL:", url) # Download file parameters download_options = { "file_types": [ "txt", "txtPlain", "jsonl", "csv", "pdfLayered", "pdfOneLayer", ], # ↓ `ingore_blank` is a typo. If you are using Umi-OCR version 2.1.4 or earlier, please use this incorrect spelling. # ↓ If you are using the latest code-built version of Umi-OCR, please use the corrected spelling `ignore_blank`. "ingore_blank": False, # Do not ignore blank pages } download_options["id"] = id data_str = json.dumps(download_options) response = requests.post(url, data=data_str, headers=headers) response.raise_for_status() res_data = json.loads(response.text) assert res_data["code"] == 100, "Failed to get download URL: {}".format(res_data) url = res_data["data"] name = res_data["name"] print("===================================") print("===== 4. Download target file =====") print("== URL:", url) # Save location for downloaded files download_dir = "/home/ubuntu/桌面/" if not os.path.exists(download_dir): os.makedirs(download_dir) download_path = os.path.join(download_dir, name) response = requests.get(url, stream=True) response.raise_for_status() # Download file size total_size = int(response.headers.get("content-length", 0)) downloaded_size = 0 log_size = 10485760 # Print progress every 10MB with open(download_path, "wb") as file: for chunk in response.iter_content(chunk_size=8192): if chunk: file.write(chunk) downloaded_size += len(chunk) if downloaded_size >= log_size: log_size = downloaded_size + 10485760 progress = (downloaded_size / total_size) * 100 print( " Downloading file: {}MB | Progress: {:.2f}%".format( int(downloaded_size / 1048576), progress ) ) print("Target file downloaded successfully: ", download_path) url = "{}/api/doc/clear/{}".format(base_url, id) print("============================") print("===== 5. Clean up task =====") print("== URL:", url) response = requests.get(url) response.raise_for_status() res_data = json.loads(response.text) assert res_data["code"] == 100, "Task cleanup failed: {}".format(res_data) print("Task cleaned up successfully.") print("======================\nProcess completed.") 将这段代码使用Flask框架部署为本地服务,用于上传文档的OCR使用,将完整的服务展现给我
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值