使用HTTPS时不显示上载进度

时间:2019-06-07 16:42:05

标签: javascript php ssl upload

我用于上传文件的这段代码可以正常工作,可以显示进度并完成工作...但是当我在具有HTTPS(SSL)的Web服务器上使用它时,文件已上传,但是进度为没有显示...如果我切换回HTTP,则会显示进度...有人知道吗?

// INDEX.PHP


<!DOCTYPE html>
<html>
<head>
<script>
/* Script written by Adam Khoury @ DevelopPHP.com */
/* Video Tutorial: http://www.youtube.com/watch?v=EraNFJiY0Eg */
function _(el){
    return document.getElementById(el);
}
function uploadFile(){
    var file = _("file1").files[0];
    // alert(file.name+" | "+file.size+" | "+file.type);
    var formdata = new FormData();
    formdata.append("file1", file);
    var ajax = new XMLHttpRequest();
    ajax.upload.addEventListener("progress", progressHandler, false);
    ajax.addEventListener("load", completeHandler, false);
    ajax.addEventListener("error", errorHandler, false);
    ajax.addEventListener("abort", abortHandler, false);
    ajax.open("POST", "upload.php");
    ajax.send(formdata);

    console.log('INIT');
}
function progressHandler(event){
    console.log('PROGRESS', event);
    _("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
    var percent = (event.loaded / event.total) * 100;
    _("progressBar").value = Math.round(percent);
    _("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
    console.log('COMPLETE', event);
    _("status").innerHTML = event.target.responseText;
    _("progressBar").value = 0;
}
function errorHandler(event){
    console.log('ERROR', event);
    _("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
    console.log('ABORT', event);
    _("status").innerHTML = "Upload Aborted";
}
</script>
</head>
<body>
<h2>HTML5 File Upload Progress Bar Tutorial</h2>
<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <input type="button" value="Upload File" onclick="uploadFile()">
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <h3 id="status"></h3>
  <p id="loaded_n_total"></p>
</form>
</body>
</html>

// UPLOAD.PHP

    $fileName = $_FILES["file1"]["name"]; // The file name
    $fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["file1"]["type"]; // The type of file it is
    $fileSize = $_FILES["file1"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true


    if (!$fileTmpLoc) { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    }


    if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){
        echo "$fileName upload is complete";
    } else {
        echo "move_uploaded_file function failed";
    }

//服务人员:


var CACHE_STATIC_NAME = 'pensadigital-estatico-v21';
var CACHE_DYNAMIC_NAME = 'pensadigital-dinamico-v21';

// Static cache
const statiAssets = [
    '/',
    '/index.php',
    '/biblioteca/js/jquery-2.1.0.min.js',
    '/biblioteca/js/jquery.form.min.js',
    '/biblioteca/js/jquery.fancybox.pack.js',
    '/biblioteca/js/scripts.js',
    '/biblioteca/js/formularios.js',
    '/biblioteca/templates/base/material_azul/jquery.fancybox.css',
                            '/biblioteca/templates/base/material_azul/estilos.css','/biblioteca/templates/fonte/roboto_condensed/fonte.css',    '/biblioteca/css/estilos.css'
]

// Install SW
self.addEventListener('install', async event=>{
    //console.log('[Service Worker] instalando SW');
    event.waitUntil(
    caches.open(CACHE_STATIC_NAME)
      .then(function(cache) {
        console.log('[Service Worker] Fazendo cache estatico');
        cache.addAll(statiAssets);
      })
    )
})

// Remove old cache files
self.addEventListener('activate', function(event) {
  console.log('[Service Worker] Activating Service Worker ....', event);
  event.waitUntil(
    caches.keys()
      .then(function(keyList) {
        return Promise.all(keyList.map(function(key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
            console.log('[Service Worker] Removing old cache.', key);
            return caches.delete(key);
          }
        }));
      })
  );
  return self.clients.claim();
});


// FETCH REQUESTS
self.addEventListener('fetch', event=>{

    url_solicitacao = event.request.url;

    // se a solicitação é de um vídeo, apenas repassar para cliente
    if ( url_solicitacao.indexOf('.mp4') > 0 || url_solicitacao.indexOf('.mp3') > 0 ){

        //console.log('[SW] Vídeo, passar direto: ', url_solicitacao);
        return;


    // Se é uma imagem, adotar estratégia de cache first depois network
    }else if ( url_solicitacao.indexOf('.jpg') > 0 || url_solicitacao.indexOf('.jpeg') > 0 || url_solicitacao.indexOf('.png') > 0 || url_solicitacao.indexOf('.gif') > 0 ){

        event.respondWith(
            caches.match(event.request)
                .then(function (response) {
                if (response) {
                    return response;
                } else {
                    return fetch(event.request)
                    .then(function (res) {
                        return caches.open(CACHE_DYNAMIC_NAME)
                        .then(function (cache) {
                            cache.put(event.request.url, res.clone());
                            return res;
                        })
                    })
                }
                })
        );


    // qualquer outro conteúdo, adotar estratégia de network first depois cache
    }else{

        event.respondWith(
            fetch(event.request)
                .then(function(res) {
                    return caches.open(CACHE_DYNAMIC_NAME)
                            .then(function(cache) {
                                cache.put(event.request.url, res.clone());
                                return res;
                            })
                })
                .catch(function(err) {
                    return caches.match(event.request);
                })
        );

    }

});

1 个答案:

答案 0 :(得分:0)

我明白了……我只是对Service Worker代码进行了更改,以忽略POST请求,如下所示:

self.addEventListener("fetch", event => {
    //This is the code that ignores post requests
    if (event.request.method === "POST") {
        return;
    }

    // the rest of the code
});