Nginx Tips: Php Uploading Progress Bar - 0010

準備工做

如今nginx-upload-module模塊已經加入到Nginx,但還不能直接使用,還有一些準備工做要作。javascript

準備JavaScript腳本

首先,下載或直接連接jQuery.js,由於模塊要配合使用jQuery來控制HTML元素顯示進度。php

<head>
...
<script type="text/javascript" src="/js/jquery.js"></script>

...
</head>

html

<head>
...

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

...
</head>

關鍵是還須要另外一個腳本:jquery.uploadProgress.js。能夠從這裏下載java


注意node


別忘了在你的頁面中包含該腳本。
一樣滴,因爲jQuery已經變化,再也不支持$.browser.safari,因此咱們須要修改jquery.uploadProgress.js。
將全部這樣的代碼:
$.browser.safari

修改爲:jquery

navigator.userAgent.match(/safari/i)

該修正參考自這裏,原意是針對IE的,能夠依樣畫葫蘆。
原文這麼說:nginx

...

as far of jquery 1.9 jQuery.browser was removed, adn admin_menu get this error:
"Uncaught TypeError: Cannot read property 'msie' of undefined" (admin_menu.js - line:223)

For quick fix use this code:
change line 223:
- if ($.browser.msie && parseInt(jQuery.browser.version) == 6) {
+ if (navigator.userAgent.match(/msie [6]/i)) {

...

修改Nginx配置文件

首先要修改/etc/nginx.conf文件,加大容許上傳的文件尺寸,並配置上傳進度報告的尺寸間隔,這裏設置爲50k一報告。git

http {
    ##
    # Basic Settings
    ##
    
    ...

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;
    
    # REV:igame@Dec-22-2013: Change size from 2m to 256m.
    client_max_body_size 256M;
    
    # REV:igame@Dec-22-2013: Followed the instruction of http://wiki.nginx.org/HttpUploadProgressModule
    upload_progress proxied 50k;

        ...

再修改/etc/nginx/sites-available/default文件中的location ~ .php$小節,根據指南,track_uploads必須是最後一行。github

location ~ \.php$ {
        ...
    # track uploads in the 'proxied' zone
        # remember connections for 30s after they finished
        track_uploads proxied 30s;
}

並添加下面的內容:ajax

location ^~ /progress {
    upload_progress_json_output;
    report_uploads proxied;
}

使用upload_progress_json_output是由於jQuery會按json模式解析數據,不加這一行將致使解析失敗,也就不能顯示進度了。

修改PHP配置

打開/etc/php5/fpm/php.ini文件,修改如下內容:

...
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On

...
;post_max_size = 8M
post_max_size = 256M

...

; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
;upload_max_filesize = 2M
upload_max_filesize = 256M

...

容許文件上傳,並容許上傳最大256M的文件。若是文件過小了,一忽兒就完畢了,也就沒法看到進度了。

編寫頁面

如今編寫上傳頁面,假設叫learn.php,內容以下:

<html>
<head>
    <script type="text/javascript" src="/js/jquery.js"></script>
    <script type="text/javascript" src="/js/jquery.uploadProgress.js"></script>
    <!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> -->
    
    <style>
        .bar {
          width: 300px;
        }
          
        #progress {
          background: #eee;
          border: 1px solid #222;
          margin-top: 20px;
        }

        #progressbar {
          width: 0px;
          height: 24px;
          background: #333;
        }
    
    </style>
</head>
<body>

<form id="form1" action="ulfile.php" method="POST" enctype="multipart/form-data">
Filename: <input type="file" name="file1" />
<input type="submit" value="Upload" />
</form>

<div id="uploading">
  <div id="progress" class="bar">
    <div id="progressbar"> </div>
    <div id="percents"></div>
  </div>
</div>

<script type="text/javascript">
$(function() {
      $('form').uploadProgress({
        /* scripts locations for safari */
        jqueryPath: "/js/jquery.js",
        uploadProgressPath: "/js/jquery.uploadProgress.js",
        start: function() {
            // Add start code here.
        },
        /* function called each time bar is updated */
        uploading: function(upload) {
            $('#percents').html(upload.percents+'%');
        },
        
        /* selector or element that will be updated */
        progressBar: "#progressbar",

        /* progress reports url */
        progressUrl: "/progress",

        /* how often will bar be updated */
        interval: 500
      });
    });
</script>
</body>
</html>

注意


該頁面可能不能在你的機器上運行,由於腳本路徑與你的實際狀況不一致。

再編寫上傳完成後的頁面,假設名字叫ulfile.php,內容以下:

<?php
  if ($_FILES["file1"])
    {
    echo "Congratulations!<br />";

        if ($_FILES["file1"]["error"] > 0)
        {
            echo "Error:" . $_FILES["file1"]["error"] . "<br />";
        }
        else
        {
        
            echo "Source File: " . $_FILES["file1"]["name"] . "<br>";
            echo "Type: " . $_FILES["file1"]["type"] . "<br>";
            echo "Size: " . round($_FILES["file1"]["size"] / 1024) . " kB<br>";
            echo "Stored in: " . $_FILES["file1"]["tmp_name"];
            echo "<br />";
        
            $uploaddir = './upload/'; // /usr/share/nginx/www/upload/';
                        // 注意,英文文件名不須要解碼,但中文須要。
            // $uploadfile = $uploaddir . basename($_FILES['file1']['tmp_name']);
            $uploadfile = $uploaddir . html_entity_decode(basename($_FILES['file1']['name']));
            
            echo "Destination:" . $uploadfile . "<br />";
        
            if (move_uploaded_file($_FILES['file1']['tmp_name'], $uploadfile))
            {
                echo "File successfully uploaded.<br />";
                /* 若是不想保存,只是測試進度條,能夠在上傳完成後當即刪除。
                if (!unlink($uploadfile))
                    echo "Can't delete the uploaded file.<br />";
                */
            }
            else
                echo "Failed to save file.<br />";
        }
    }

注意,若是遇到目錄問題,好比這裏使用upload目錄,而你沒有,你須要創建這樣的目錄並設置至關權限(root)。
好了,如今能夠心情的享受你的上傳進度條了,當心不要爆了你的硬盤。


Tips


問題主要集中在路徑上,好比js的路徑,目錄的權限,致命的413錯誤等。
相關文章
相關標籤/搜索