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

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

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

要使用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), 玩得开心!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值