使用PHP上传Sweet Alert 2 jQuery文件 [英] Sweet Alert 2 jQuery file upload with php

查看:114
本文介绍了使用PHP上传Sweet Alert 2 jQuery文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jQuery和php在Sweet Alert 2模式下创建文件上传器.这是我的代码,但是不起作用:如何使它工作?

I'm trying to create a file uploader inside a Sweet Alert 2 modal with jQuery and php. Here's my code, but it isn't working: how can I get this working?

谢谢

HTML(使用Sweet Alert 2打开模式的按钮):

HTML (the button to open the modal with Sweet Alert 2):

<button class="bx--btn bx--btn--primary" type="button" id="swal_upload">Apri</button>

JavaScript:

JavaScript:

$('#swal_upload').click(function(){
    var api = 'api/UploadFile.php';
    swal({
        title: "Carica immagine",
        html: '<input id="fileupload" type="file" name="userfile">'
    }).then(function() {
        var formData = new FormData();
        formData.append('userfile', $('#fileupload').val().replace(/.*(\/|\\)/, ''));
        console.log(formData);
        $.ajax({
          type: 'POST',
          url: api,
          data: formData,
          dataType: 'json',
          processData: false,
          contentType: false,
          headers: {"Content-Type":"form-data"},
          async: true,
          success: function(result){
            console.log("OK client side");
            console.log(result.Response);
          }
        });
    })
  });

php(api/UploadFile.php):

php (api/UploadFile.php):

$entered = "PHP started";

$tmpFilePath = $_FILES['userfile']['tmp_name'];

$uploaddir = 'public/';

  if ($tmpFilePath != ""){
    $newFilePath = $uploaddir . basename($_FILES['userfile']['name']);

    if(move_uploaded_file($tmpFilePath, $newFilePath)) {
      $uploaded = "Upload OK server side";
    } else {
      $uploaded = "Upload failed server side";
    }
  }

  // Prepare response, close connection and send response to front-end
  $array['Response'] = array(
    'entered' => $entered,
    'tmp_path' => $tmpFilePath,
    'new_path' => $newFilePath,
    'file_name' => $_FILES['file']['name'],
    'uploaded' => $uploaded
  );

  echo json_encode($array);

我在控制台中的输出是:

The output I have in the console is:

FormData {} 原始:FormData 好的客户端 {输入:"PHP已启动",tmp_path:null,new_path:null,file_name:null,上载:null} 输入:"PHP启动" file_name:null new_path:null tmp_path:null 上传:空 proto :对象

FormData {}proto: FormData OK client side {entered: "PHP started", tmp_path: null, new_path: null, file_name: null, uploaded: null} entered:"PHP started" file_name:null new_path:null tmp_path:null uploaded:null proto:Object

如您所见,php已启动,但是没有文件传递到服务器.

As you can see the php starts, but no file is passed to the server.

推荐答案

我使用了基于文件读取器/ FormData 对象. 当使用Sweetalert的输入文件类型时,将创建具有swal2-file css类的输入元素:

I have used a solution based on the input file type from Sweetalert 2 and the FileReader/FormData objects from the view side. When you use an input file type of Sweetalert, an input element with the swal2-file css class will be created:

然后,您可以使用Sweetalert事件onBeforeOpen通过FileReader对象读取文件数据.最后,您可以使用带有FormData对象的Ajax请求来发送文件. 这将是js来源:

Then you can use the Sweetalert event onBeforeOpen to read the file data through the FileReader object. Finally you can send the file using ajax request with the FormData object. This would be the js source:

$('#swal_upload').click(function() {
     Swal({
        title: 'Select a file',
        showCancelButton: true,
        confirmButtonText: 'Upload',
        input: 'file',
        onBeforeOpen: () => {
            $(".swal2-file").change(function () {
                var reader = new FileReader();
                reader.readAsDataURL(this.files[0]);
            });
        }
    }).then((file) => {
        if (file.value) {
            var formData = new FormData();
            var file = $('.swal2-file')[0].files[0];
            formData.append("fileToUpload", file);
            $.ajax({
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                method: 'post',
                url: '/file/upload',
                data: formData,
                processData: false,
                contentType: false,
                success: function (resp) {
                    Swal('Uploaded', 'Your file have been uploaded', 'success');
                },
                error: function() {
                    Swal({ type: 'error', title: 'Oops...', text: 'Something went wrong!' })
                }
            })
        }
    })
})

在服务器端,使用Laravel Php框架,您可以通过以下函数获取文件:

From the server side, using Laravel Php framework, you can get the file through a function like this:

public function uploadFile(Request $request)
{
    if ($request->hasFile('fileToUpload')) {
        $file_name = $request->file('fileToUpload')->getClientOriginalName();
        $earn_proof = $request->file('fileToUpload')->storeAs("public/files/", $file_name);
    }

    return response()->json(['result' => true], 200);
}

这篇关于使用PHP上传Sweet Alert 2 jQuery文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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