简体   繁体   English

使用Put Http方法上传文件

[英]File upload using Put Http method

I want to upload a files to a remote server.我想将文件上传到远程服务器。 For this I have read that we could use put method to upload the file.为此,我读到我们可以使用 put 方法上传文件。

The user will be provided a form where they can upload one or 2 files.将向用户提供一个表单,他们可以在其中上传一个或 2 个文件。 This file should be uploaded to the other server.此文件应上传到其他服务器。

The code I have used for file upload using http put is as follows:我使用http put上传文件的代码如下:

$curl = curl_init($api_url);
$data = array(
  'filename' => 'filename.html',   
  );
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
// Make the REST call, returning the result
$response = curl_exec($curl);
if (!$response) {
    die("Connection Failure.n");
}

The put request is sent but the file does not get uploaded as required.已发送放置请求,但未按要求上传文件。 The file name goes as data.文件名作为数据。 Also the filename.html file is in the root location of the webserver.此外,filename.html 文件位于网络服务器的根位置。 How do I upload a file?如何上传文件?

  1. It seems that you didn't send contents of the file.您似乎没有发送文件的内容。
  2. Accepting your request as a upload is completely up to the server.接受您的上传请求完全取决于服务器。 Ask the server's administrator how to upload a file or read the API document for the server if is provided.询问服务器管理员如何上传文件或阅读服务器的API文档(如果提供)。

If you're using PHP you can use the code below:如果您使用的是 PHP,则可以使用以下代码:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM