使用PHP的Multipart / form-data

时间:2015-07-22 22:14:13

标签: php html multipartform-data html-form

我编写了一个multipart / form-data html,用户可以直接上传到AWS S3。但是,我希望使用PHP fwrite()来创建要上载的文件。我在页面加载时使用PHP生成csv,然后我希望该文件自动用于multipart / form-data上传。这是代码:

 <form action="https://s3.amazonaws.com/my.data" method="post" enctype="multipart/form-data">
  <input type="hidden" name="key" value="uploads/${filename}">
  <input type="hidden" name="AWSAccessKeyId" value="xxxxxxxx"> 
  <input type="hidden" name="acl" value="private"> 
  <input type="hidden" name="success_action_redirect" value="http://thanks.html">
  <input type="hidden" name="policy" value="xxxxxxxxxx">
  <input type="hidden" name="signature" value="xxxxxxxxx">
  <input type="hidden" name="Content-Type" value="">
  <!-- Include any additional input fields here -->

  File to upload to S3: 
  <input name="file" type="file"> 
  <br> 
  <input type="submit" value="Upload File to S3"> 
</form> 

 <?php
 $email = "testemail@gmail.com";
 $art_fair = 0;

//this is where the creating of the csv takes place
$cvsData = $email . "," . $art_fair . "\n";

$fp = fopen("formTest.csv","a"); // $fp is now the file pointer to new file to create

if($fp){
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
?>

我正在试图找出如何将它们组合在一起以使其工作。谢谢!

1 个答案:

答案 0 :(得分:1)

当您实际上不想要任何文件被选中时,呈现表单的重点是什么? 使用这种方法有很多缺陷。最重要的是,你邀请人们玩你的凭证。此外,你没有从客户端获取任何输入。所以为什么不直接生成csv文件和通过cURL通过POST请求上传!!! 使用curl也可以提高速度。

以下是如何做到的:

//Make an array of your POST Parameters
$params=array(
   "file"=>realpath('formTest.csv'),  //This will generate the path to csv file you want to send 
  "AWSAccessKeyId"=>'xxxxxx',
  ......
  ......
 );

// initialise the curl request
$request = curl_init('https://s3.amazonaws.com/my.data');

// send a file
curl_setopt($request, CURLOPT_POST, true);
curl_setopt(
    $request,
    CURLOPT_POSTFIELDS,http_build_query($params)
  );

//Set The Header to Multipart
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));

// output the response
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
echo curl_exec($request);

// close connection
curl_close($request);

在编写csv文件后添加此代码。