如何在php或symfony中使用jQuery ajax上传文件

用传统的方式发送文件是一种简单的任务(表单, 文件输入和提交按钮)。但是, 当我们想使用javascript进行操作时并不是那么容易, 也不是那么直观。要完成此任务, 我们需要jQuery(或使用xmlHttpRequest函数)和耐心。

html表单需要如下所示, 一个简单的文件输入(text参数是可选的, 仅用于证明我们可以发送更多信息, 而不仅仅是文件)。

<form id="myform" method="post">
  <input type="text" name="username" />
  <input type="file" name="upload" />
</form>

要使用ajax发送文件, 你需要发送ajax请求以发送POST数据, 以下代码将为你解决问题:

注意:在此示例中, 我们期望从服务器json(dataType:json)开始, 你可以发送自己的响应类型。

var form = document.getElementById("myform");
// or with jQuery
//var form = $("#myform")[0];

$.ajax({
  url:"/web-service/that/will-process/our-image",   data: new FormData(form), // the formData function is available in almost all new browsers.
  type:"post",   contentType:false,   processData:false,   cache:false,   dataType:"json", // Change this according to your response from the server.
  error:function(err){
        console.error(err);
  },   success:function(data){
       console.log(data);      
  }, complete:function(){
   console.log("Request finished.");

  }
});

变量形式将是形式的节点元素。然后, 我们只需要在后端检索文件即可。

我们将使用控制器的request对象检索文件。然后, 我们将其移动并返回JSON响应。

// Important to use these statemenets, the json response is optional for our response.
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

public function retrieveAction(Request $request){
   // retrieve the file with the name given in the form.
   // do var_dump($request->files->all()); if you need to know if the file is being uploaded.
   $file = $request->files->get('upload');
   $status = array('status' => "success", "fileUploaded" => false);
  
   // If a file was uploaded
   if(!is_null($file)){
      // generate a random name for the file but keep the extension
      $filename = uniqid().".".$file->getClientOriginalExtension();
      $path = "/path/where/we/want-to-save-the-file";
      $file->move($path, $filename); // move the file to a path
      $status = array('status' => "success", "fileUploaded" => true);
   }

   return new JsonResponse($status);
}
$info = pathinfo($_FILES['upload']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "thenamethat you want.".$ext; 

$target = 'path-where-to-save-the-file/'.$newname;
move_uploaded_file( $_FILES['upload']['tmp_name'], $target);

你可以根据自己的需要设置后端(例如, 如果你不使用php), 玩得开心!

来源:

https://www.srcmini02.com/59699.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?