Posting Raw Image Data as Multipart/Form-Data in Curl

Posting raw image data as multipart/form-data in curl

In case anyone had the same problem: check this as @PravinS suggested. I used the exact same code as shown there and it worked for me perfectly.

This is the relevant part of the server code that helped:

if (isset($_POST['btnUpload']))
{
$url = "URL_PATH of upload.php"; // e.g. http://localhost/myuploader/upload.php // request URL
$filename = $_FILES['file']['name'];
$filedata = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
if ($filedata != '')
{
$headers = array("Content-Type:multipart/form-data"); // cURL headers for file uploading
$postfields = array("filedata" => "@$filedata", "filename" => $filename);
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $postfields,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true
); // cURL options
curl_setopt_array($ch, $options);
curl_exec($ch);
if(!curl_errno($ch))
{
$info = curl_getinfo($ch);
if ($info['http_code'] == 200)
$errmsg = "File uploaded successfully";
}
else
{
$errmsg = curl_error($ch);
}
curl_close($ch);
}
else
{
$errmsg = "Please select the file";
}
}

html form should look something like:

<form action="uploadpost.php" method="post" name="frmUpload" enctype="multipart/form-data">
<tr>
<td>Upload</td>
<td align="center">:</td>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td> </td>
<td align="center"> </td>
<td><input name="btnUpload" type="submit" value="Upload" /></td>
</tr>

Adapt multipart/form-data request to curl with image and json in the same request

I also fail to understand the key that is next to WebKitFormBoundary is a value that seems random, is it just a separator? can i use anything?

yes and yes and practically speaking yes. it's supposed to be a random-guaranteed-unique string used as separator to signal start and end of forms.. if you know beforehand that none of your uploads contains the string stackoverflow, you could use Content-Type: multipart/form-data; boundary=stackoverflow for example (but this may break if you upload a file actually containing the string stackoverflow !), but you should let curl generate that string automatically, rather than specifying it yourself, curl will auto-generate a string that is practically guaranteed to be unique.

I have removed the headers that I considered irrelevant

... if you guessed wrong, the server may give you an error for missing a required header. assuimg that you didn't make any mistakes in removing irrelevant headers though, i think it's

curl 'https://localhost'\
--form "image=@image.jpg;type=image/jpeg"\
--form "item=@blob;type=application/json"

the request generated by that command is roghly:

POST / HTTP/1.1
Host: localhost
User-Agent: curl/7.81.0
Accept: */*
Content-Length: 359
Content-Type: multipart/form-data; boundary=------------------------7d0262831ce8f248

--------------------------7d0262831ce8f248
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: image/jpeg

image.jpg content

--------------------------7d0262831ce8f248
Content-Disposition: form-data; name="item"; filename="blob"
Content-Type: application/json

["json lol"]

--------------------------7d0262831ce8f248--

as you can see above, Accept: */* is curl's default accept-header anyway, so there's no need to specify it, and curl auto-generated the boundary ------------------------7d0262831ce8f248 so there's no need to manually specify a boundary either.

What is the right way to POST multipart/form-data using curl?

The following syntax fixes it for you:

curl -v -F key1=value1 -F upload=@localfilename URL

using curl for multipart/form-data with a file upload

curl -X POST  -F fieldNameHere=@myfile.html  http://myapi.com/

or

-X POST is implied by -F (per comment), quotes are optional

curl -F "fieldNameHere=@myfile.html"  http://myapi.com/

post multipart/form-data variable and image using curl

When you upload a file to server using curl, you need to specify the @ sign before the file path. For example this image file:

$img = '/var/tmp/someimg.jpg';  // must be full path

Then in your post data, it should be:

'your_file' => '@' . $img,

Also, remove the following header from your curl code. Curl will automatically set this header with length based on your parameters.

curl_setopt($ch , CURL_HTTPHEADER , "Content-Type: multipart/form-data" );

Finally make sure your other parameter values are correct. And, also enable the verbose mode, so that you can see the output from curl curl_setopt($ch, CURLOPT_VERBOSE, 1);

Multipart form file upload POST PHP cURL

Hi I have figured out the problem.

My params were not set correct on the api endpoint. Need to set a note_id(c_id)

But issue I am having now is posting all data at once. I am posting file after the note has been created thus generating the note id for me for posting file. Can anyone help with that? I can post a new question.

See updated code below:

//$orgID = (is_numeric($_POST['orgID']) ? (int)$_POST['orgID'] : 0);
//$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
//$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);

$noteID = (isset($_POST['noteID']) ? $_POST['noteID'] : null);

$localFile = $_FILES['file']['tmp_name'];
$fp = fopen($localFile, 'r');

$curl = curl_init();

$cfile = new CURLFILE($_FILES['file']['tmp_name'], $_FILES['file']['type'], $_FILES['file']['name']);
$data = array();
//$data["TITLE"] = "$noteTitle";
//$data["BODY"] = "$noteBody";
//$data["LINK_SUBJECT_ID"] = "$orgID";
//$data["LINK_SUBJECT_TYPE"] = "Organisation";
$data['FILE_ATTACHMENTS'] = $cfile;

curl_setopt_array($curl, array(
CURLOPT_UPLOAD => 1,
CURLOPT_INFILE => $fp,
CURLOPT_NOPROGRESS => false,
CURLOPT_BUFFERSIZE => 128,
CURLOPT_INFILESIZE => filesize($localFile),
CURLOPT_URL => "https://api.insight.ly/v2.1/Notes/?c_id=" . $noteID . "&filename=" . $_FILES['file']['name'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"authorization: Basic xxx",
"cache-control: no-cache",
"content-type: multipart/form-data",
"postman-token: xxx"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

HTML

<form method="POST" action="formSend.php" enctype="multipart/form-data">
//<input type="text" value="" name="orgID">
//<input type="text" value="" name="noteTitle">
//<input type="text" value="" name="noteBody">
<input type="text" value="" name="noteID">
<input name="file" type="file" id="file"/>
<input type="submit" value="Submit" name="btnUpload"/>
</form>

If anyone is interested this is my solution for using fpdf to generate a PDF document from the web form then auto send, instead of the file upload. FPDF file ---> send via CURL automatically NOT with file upload

How to POST a Multipart form with image and a JSON object containing an array of objects using CURL

This is how I got it to work:

curl --request POST "https://my-server/post-url" \
--header 'Accept: application/json' \
--form "score_id=153A6D67" \
--form 'inputs[0][type]=hits' \
--form 'inputs[0][value]=4' \
--form 'inputs[1][type]=miss' \
--form 'inputs[1][value]=3' \
--form "uploaded_image=@$IMAGE"


Related Topics



Leave a reply



Submit