用PHP上传文件基本都是临时存储,之后上传,怎么用PHP模拟浏览器以数据流形式上传文件

思路及代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//网址 参数 文件
function upload($url, $p, $file) {
$param = [
//此处根据实际文件的上传的 name 填写
'fileData' => file_get_contents(realpath($file)),
];
if (!empty($p)) {
arrary_merge($p, $param);
}
$delimiter = uniqid();
$data = '';
$eol = "\r\n";
$upload = $param['fileData'];
unset($param['fileData']);
foreach ($param as $name => $content) {
$data .= "--" . $delimiter . "\r\n"
. 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
. $content . "\r\n";
}
// 拼接文件流 name="fileData"; filename="1.png"' 根据实际的文件 name 和名字填写 或写个变量
//'Content-Type: image/gif'可改为'Content-Type:application/octet-stream' 由于我是测试的网站必须为 gif 所以就这样吧先
$data .= "--" . $delimiter . $eol
. 'Content-Disposition: form-data; name="fileData"; filename="1.png"' . "\r\n"
. 'Content-Type: image/gif' . "\r\n\r\n";

$data .= $upload . "\r\n";
$data .= "--" . $delimiter . "--\r\n";
$post_data = $data;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
"Content-Type: multipart/form-data; boundary=" . $delimiter,
"Content-Length: " . strlen($post_data),
]);
$response = curl_exec($curl);
curl_close($curl);
return $response;
}

请根据实际情况进行实际调用