在php中使用multipart/form-data请求发送文件 [英] Send file using multipart/form-data request in php

查看:240
本文介绍了在php中使用multipart/form-data请求发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将图像资源存储在变量中,我需要使用其 http API 和 PHP 将其发送到服务器.我必须发送内容类型为 multipart/form-data 的请求.所以,我需要发出类似的请求,就像发送带有文件输入和 enctype=multipart/form-data 属性的表单一样.我试过这个:

I have image resource stored in variable which I need to send to server using its http API and PHP. I have to send request with content type multipart/form-data. So, I need to make similiar request as when form with file input and enctype=multipart/form-data attribute is sent. I tried this:

<?php
$url = 'here_is_url_for_web_API';
$input = fopen('delfin.jpg','r');       
$header = array('Content-Type: multipart/form-data');
$resource = curl_init();
curl_setopt($resource, CURLOPT_URL, $url);
curl_setopt($resource, CURLOPT_USERPWD, "user:password");
curl_setopt($resource, CURLOPT_HTTPAUTH, CURLAUTH_ANYSAFE);
curl_setopt($resource, CURLOPT_HTTPHEADER, $header);
curl_setopt($resource, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($resource, CURLOPT_BINARYTRANSFER, true );
curl_setopt($resource, CURLOPT_INFILESIZE, 61631);
curl_setopt($resource, CURLOPT_INFILE, $input);
$result = curl_exec($resource);
curl_close($resource);
var_dump($result);
?>

我不知道响应应该是什么样子,但这会返回:http 状态 405并且报错为:请求的资源不允许指定的HTTP方法().

I don't know how exactly response should look like but this returns: http status 405 and error report is: The specified HTTP method is not allowed for the requested resource ().

推荐答案

如果您使用 CURL,您只需:

If you work with CURL, you have to just:

1、设置header 'Content-Type'为'multipart/form-data;'

1, set header 'Content-Type' as 'multipart/form-data;'

2、设置curl的'RETURNTRANSFER'选项为true(使用curl的option方法)

2, set option 'RETURNTRANSFER' of curl to true (use option method of curl)

3、设置curl的'POST'选项为true(使用curl的option方法)

3, set option 'POST' of curl to true (use option method of curl)

4、获取你的文件源(你从 PHP 中的 fopen 得到的):

4, get source of your file (what you get from fopen in PHP):

$tempFile = tempnam(sys_get_temp_dir(), 'File_');                
file_put_contents($tempFile, $source);
$post = array(
    "uploadedFile" => "@" . $tempFile, //"@".$tempFile.";type=image/jpeg",
);

5、使用CURL的post方法,参数在$post变量中

5, use post method of CURL with parameter in $post variable

这篇关于在php中使用multipart/form-data请求发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆