I have been trying to implement a functionality that is written in Java, for uploading a file via PUT HTTP request.
Here is my sample Java code:
import com.google.common.io.Files;
public void uploadFile() {
final makeRestRequest makeUploadRequest = makeRequestTo(upload_file_location)
.method("PUT")
.addHeader(new HttpHeader("Accept", "application/json"))
.addHeader(new HttpHeader("Content-Type", "application/zip"))
.body(Files.newInputStreamSupplier(new java.io.File("/sample_file.zip")))
.build();
final getRestResponse uploadResponse = makeUploadRequest.fetchResponse();
}
I am looking for a similar variant of the php code, that can make a HTTP PUT call to upload a file, but i am not sure what to use for the newInputStreamSupplier. Here is my sample php code, that makes a PUT call to upload file using CURL, but fails to get a response:
<?php
$url = upload_file_location;
$localfile = "sample_file.zip";
$fp = fopen ($localfile, "rb");
$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$headers = array();
$headers[] = 'Content-Type: application/zip';
$headers[] = 'Accept: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($localfile));
$http_result = curl_exec($ch);
?>
I get an error saying: "File content is empty". Does anyone have an idea of what i am doing wrong?
Well, i figured out a solution for my question. I should pass the full path to the file in the CURL filesize header:
curl_setopt($ch, CURLOPT_INFILESIZE, filesize(realpath($localfile));
Also, I had to add the below CURL header to transfer file data as binary:
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
The solution mentioned in this question helped me.