douyi3307 2018-01-17 14:13
浏览 117
已采纳

Sweet Alert 2使用php上传jQuery文件

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?

Thank you

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:

$('#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);

The output I have in the console is:

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

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

  • 写回答

1条回答 默认 最新

  • doumei8258 2019-02-01 14:21
    关注

    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: enter image description here

    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!' })
                    }
                })
            }
        })
    })
    

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算