[英]Is there a config for uploading big files in Django with a progress bar on IIS?
我正在使用Django 2.2和IIS(Fastcgi)创建一个网页来上传带有进度条的大文件。 我使用以下链接中的代码:
https://djangosnippets.org/snippets/678/
https://djangosnippets.org/snippets/679/
我的应用程序在开发环境中运行良好,但是在生产环境中,当我观看控制台浏览器时,它始终返回“ null”值,并且未显示进度条,但文件已上传到服务器并返回“ 200” 。 为什么? 这是我应该在IIS或Web上添加的另一个配置?
以下代码在控制台中返回Null:
def upload_progress(request):
"""
Return JSON object with information about the progress of an upload.
"""
progress_id = ''
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if progress_id:
cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
data = cache.get(cache_key)
return HttpResponse(json.dumps(data))
else:
return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.')
view.py:
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseServerError
from django.core.cache import cache
from .forms import UploadFile
from upbar.UploadProgressbar import UploadProgressCachedHandler
from django.views.decorators.csrf import csrf_exempt, csrf_protect
import json
@csrf_exempt
def upload_file(request):
request.upload_handlers.insert(0, UploadProgressCachedHandler(request))
return _upload_file(request)
# Create your views here.
def _upload_file(request):
if request.method == 'POST':
form = UploadFile(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
return HttpResponse('200')
else:
form = UploadFile()
return render(request, 'upbar/home.html', {'form': form})
def handle_uploaded_file(f):
with open(f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
# A view to report back on upload progress:
#
def upload_progress(request):
"""
Return JSON object with information about the progress of an upload.
"""
progress_id = ''
if 'X-Progress-ID' in request.GET:
progress_id = request.GET['X-Progress-ID']
elif 'X-Progress-ID' in request.META:
progress_id = request.META['X-Progress-ID']
if progress_id:
cache_key = "%s_%s" % (request.META['REMOTE_ADDR'], progress_id)
data = cache.get(cache_key)
return HttpResponse(json.dumps(data))
else:
return HttpResponseServerError('Server Error: You must provide X-Progress-ID header or query param.')
setup.py:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '4u%-od)a^a-=)_g_@^_v1sssv%)s@95f25oifgpixtx8!f=*7v'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'upbar.apps.UpbarConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'uploadbar.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'uploadbar.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# DATA_UPLOAD_MAX_MEMORY_SIZE = 2147483648
form.py:
from django import forms
class UploadFile(forms.Form):
"""UploadFile definition."""
file = forms.FileField()
UploadProgressbar.py:
from django.core.files.uploadhandler import TemporaryFileUploadHandler
from django.core.cache import cache
import time
class UploadProgressCachedHandler(TemporaryFileUploadHandler):
"""
Tracks progress for file uploads.
The http post request must contain a header or query parameter, 'X-Progress-ID'
which should contain a unique string to identify the upload to be tracked.
"""
def __init__(self, request=None):
super(UploadProgressCachedHandler, self).__init__(request)
self.progress_id = None
self.cache_key = None
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
self.content_length = content_length
if 'X-Progress-ID' in self.request.GET:
self.progress_id = self.request.GET['X-Progress-ID']
elif 'X-Progress-ID' in self.request.META:
self.progress_id = self.request.META['X-Progress-ID']
if self.progress_id:
self.cache_key = "%s_%s" % (
self.request.META['REMOTE_ADDR'], self.progress_id)
cache.set(self.cache_key, {
'length': self.content_length,
'uploaded': 0
}, 30)
def new_file(self, field_name, file_name, content_type, content_length, charset=None, content_typ_extra=None):
pass
def receive_data_chunk(self, raw_data, start):
if self.cache_key:
data = cache.get(self.cache_key)
data['uploaded'] += self.chunk_size
cache.set(self.cache_key, data)
return raw_data
def file_complete(self, file_size):
if self.cache_key:
data = cache.get(self.cache_key)
data['uploaded'] = self.content_length
cache.set(self.cache_key, data)
# sleep for give time to receive final response in request progress bar
time.sleep(3)
def upload_complete(self):
if self.cache_key:
cache.delete(self.cache_key)
upload.js:
$(document).ready(function () {
function gen_uuid() {
var uuid = ""
for (var i = 0; i < 32; i++) {
uuid += Math.floor(Math.random() * 16).toString(16);
}
return uuid
}
uuid = gen_uuid();
// form submission
$('form').submit(function () {
// Prevent multiple submits
if ($.data(this, 'submitted')) return false;
// Append X-Progress-ID uuid form action
this.action += (this.action.indexOf('?') == -1 ? '?' : '&') + 'X-Progress-ID=' + uuid;
$('<div class="progress"> <div id="progressBar" class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"> 0% </div></div>').appendTo('body')
upload_progress_url = '/upload_progress/'
function update_progress_info() {
$.getJSON(upload_progress_url, {
'X-Progress-ID': uuid
}, function (data, status) {
console.log(data)
if (data) {
var progress = Math.round((parseInt(data.uploaded) * 100) / parseInt(data.length));
$('#progressBar').attr('aria-valuenow', progress).css('width', progress + '%').text(progress + '%');
}
window.setTimeout(update_progress_info, 100);
}).fail(function (jqxhr, textStatus, error) {
console.log('jqxhr errorrr ==================')
console.log(jqxhr);
console.log('==================')
console.log('textstatus ==================')
console.log(textStatus);
console.log('==================')
console.log('jqxhr.responsetext errorrr ==================')
console.log(jqxhr.responseText)
console.log('==================')
console.log('errorrr ==================')
console.log(error);
});
}
window.setTimeout(update_progress_info, 100);
$.data(this, 'submitted', true); // mark form as submitted.
return true;
});
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
{% load static %}
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Home</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
Noting Here
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
<script src="{% static 'upbar/jquery-3.4.1.min.js' %}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="{% static 'upbar/upload.js' %}"></script>
</body>
</html>
这是我的控制台浏览器的屏幕截图: 。
您可以使用以下选项来提高iis中的文件上传限制:
1)在web.config中修改maxAllowedContentLength设置
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483648" />
</requestFiltering>
</security>
</system.webServer>
2)使用iis请求过滤功能:
3)手动编辑ApplicationHost.config文件
<requestLimits maxAllowedContentLength ="<length>" />
请不要忘记在进行更改后重新启动iis服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.