【问题标题】:Sweet Alert 2 jQuery file upload with phpSweet Alert 2 使用 php 上传 jQuery 文件
【发布时间】:2018-01-17 14:13:33
【问题描述】:

我正在尝试使用 jQuery 和 php 在 Sweet Alert 2 模式中创建文件上传器。这是我的代码,但它不工作:我怎样才能让它工作?

谢谢

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

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

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):

$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);

我在控制台的输出是:

FormData {}原型:FormData 好的客户端 {输入:“PHP 开始”,tmp_path:null,new_path:null,file_name:null,上传:null} 输入:“PHP 开始” 文件名:空 新路径:空 tmp_path:null 上传:空 原型:对象

如您所见,php 启动了,但没有文件传递到服务器。

【问题讨论】:

  • 当问题陈述很简单时,很难提供解决方案,"it doesn't work"。请edit您的问题更完整地描述您预期会发生什么以及这与实际结果有何不同。请参阅 How to Ask 以获取有关什么是好的解释的提示。
  • 这种方式不能使用ajax上传数据。尤其是 "Content-Type":"form-data"
  • @PaunNarcisIulian 你有解决办法吗?

标签: javascript php jquery file


【解决方案1】:

我使用了基于Sweetalert 2输入文件 类型和视图侧的FileReader/FormData 对象的解决方案。 当您使用 Sweetalert 类型的输入文件时,将创建一个带有 swal2-file css 类的输入元素:

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

$('#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 框架,你可以通过如下函数获取文件:

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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    相关资源
    最近更新 更多