В прошлом месяце Брис Фигерео выпустил небольшой модуль Nginx, который отслеживает продвижение, загружает прохождение Nginx. Как mod_uploadprogress Лайттпда очень хорошо иметь полномочие, берут ответственность за сообщение о продвижении.Last month Brice Figureau released a little Nginx module which tracks the progress of uploads going through Nginx. Like Lighttpd's mod_uploadprogress it's very nice to have the proxy take responsibility for reporting the progress.

Nginx загружают модуль продвижения, добавляют track_uploads и report_uploads директивы, которые делают то, что они говорят относительно олова. Когда пользователь представляет форму местоположению, поддерживающему track_upload, мы также посылаем дополнительный параметр X-Progress-ID с уникальным id для этого, загружают. Просьбы, обращенные к местоположению, поддерживающему report_uploads (типично / загружает), возвратят JSON с текущим продвижением для загружения. Заголовок X-Progress-ID добавлен к запросам ajax идентифицировать, которые загружают, мы желаем знать статус.The Nginx upload progress module adds track_uploads and report_uploads directives which do what they say on the tin. When the user submits a form to the location supporting track_upload, we also send an extra X-Progress-ID parameter with a unique id for that upload. Requests made to the location supporting report_uploads (typically /uploads) will return JSON with the current progress for an upload. The X-Progress-ID header is added to the ajax requests to identify which upload we're wanting to know the status of.
Наличие следа Nginx, продвижение обходит проблему с использованием merb, загружает метод продвижения. Nginx (un) к счастью не проводит загружение к своему предназначению, пока это полностью не закончило загружение. Так, когда Вы загружаете файл, Ваше заявление Merb не будет знать об этом, пока это не было, загружают к Nginx и проведенный. Единственное схватывание с этим целым процессом - возможность маленькой задержки, поскольку Merb обращается с запросом, как только загружение полно. Если Вы используете Рельсы однако, это может быть преимуществом, поскольку это не будет связано загружением, поскольку это случается в в реальном времени.Having Nginx track the progress gets around an issue with using the merb upload progress method. Nginx (un)fortunately does not pass along the upload to its destination until it has fully completed uploading. So when you upload a file, your Merb application won't know about it until it has been upload to Nginx and passed along. The only gripe with this whole process is the possibility of a small delay as Merb handles the request once the upload is complete. If you're using Rails however this can be an advantage, as it won't be tied up by the upload as it happens in realtime.
Чтобы получить это все движение, Вы будете сначала хотеть загрузить Nginx, загружают модуль продвижения и повторно собирают Nginx со следующим, формируют выбор.To get this all going you'll first want to download the Nginx upload progress module and recompile Nginx with the following configure option.
- add-module=path/to/nginx_uploadprogress_module--add-module=path/to/nginx_uploadprogress_module
Определите местонахождение и откройте свой nginx файл конфигурации и добавьте в upload_progress, track_uploads и report_uploads директивы.Locate and open your nginx configuration file and add in the upload_progress, track_uploads and report_uploads directives.
Если Вы соберетесь загрузить файлы какого-нибудь значительного размера, то Вы будете также хотеть к max_body_side кое к чему разумному.If you're going to upload files of any considerable size you'll also want to the max_body_side to something reasonable.
http {http { upload_progress proxied 1 м.;upload_progress proxied 1m; сервер {server { слушайте 80;listen 80; server_name _ *;server_name _ *; корень/usr/local/www;root /usr/local/www; местоположение / {location / { proxy_pass http://127.0.0.1:4000;proxy_pass http://127.0.0.1:4000; track_uploads proxied 30-ые;track_uploads proxied 30s; client_max_body_size 500 м.;client_max_body_size 500m; } местоположение ^ ~ / прогрессирует {location ^~ /progress { report_uploads proxied;report_uploads proxied; } } }
Nginx теперь готов отследить, загружает! Произведите Merb, проектируют и добавляют, что новое загружает диспетчера.Nginx is now ready to track uploads! Generate a Merb project and add a new upload controller.
class Uploader < Application
def index
render
end
def upload
FileUtils.mv params[:file][:tempfile].path, \
MERB_ROOT+"/files/#{params[:file][:filename]}"
end
end
Тогда добавьте загружать представление.Then add the upload view.
<div id="pandaloader">
<div id="uploader">
<form id="upload" enctype="multipart/form-data" \
action="/uploader/upload" method="post">
<input name="file" type="file">
<input type="submit" value="Upload">
</form>
</div>
<div id="uploading">
<div id="progress" class="bar">
<div id="progressbar"> </div>
</div>
</div>
</div>
В заголовке расположения Вашего заявления Вы также должны будете включать javascript и css.In the header of your application's layout you'll also need to include the javascript and css.
<%= css_include_tag 'upload' %>
<%= js_include_tag 'jquery' %>
<%= js_include_tag 'jquery.nginxUploadProgress.js' %>
Кроме jQuery, Вы заметите jquery.nginxUploadProgress.js плагин, который был включен. Это - небольшая jQuery библиотека, которая подвергнет сомнению Nginx для продвижения upload и обновит длину бара продвижения соответственно. Захватите файл здесь: jquery.nginxUploadProgress.jsAside from jQuery, you'll notice the jquery.nginxUploadProgress.js plugin which has been included. This is a little jQuery library which will query Nginx for the upload's progress and update the length of the progress bar accordingly. Grab the file here: jquery.nginxUploadProgress.js
Вот некоторое моделирование для бара продвижения.Here is some styling for the progress bar.
.bar {
width: 300px;
}
#progress {
background: #eee;
border: 1px solid #222;
}
#progressbar {
width: 0px;
height: 24px;
background: #333;
}
Поместите все они вместе, и у Вас будет большой небольшой бар продвижения для, загружает!Put all these together and you'll have a great little progress bar for uploads!
