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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵