我有一个Web应用程序,其中的一项功能是将文件上传到特定系统中。 Django使用requests
python模块通过Ajax调用将文件上传到远程API。
当我在本地运行该应用程序时,此方法运行良好,但是当我通过Nginx运行该应用程序时,当我尝试上传文件时,总是会收到以下错误消息
[error] 22665#0: *254004 upstream prematurely closed connection while reading response header from upstream,
client: xxx.xxx.xx.xx, server: redacted.com,
request: "POST /report/ajax/upload_file/ HTTP/2.0",
upstream: "http://unix:/var/www/webapp.sock:/report/ajax/upload_file/",
host: "redacted.com",
referrer: "https://redacted.com/report/key/sha256/"
开发人员工具中出现502
错误
POST https://redacted.com/report/ajax/upload_file/ 502
进行ajax调用的客户端代码是
function handleUploadButton() {
$('#upload-button').on('click', function() {
var data = new FormData();
var file = $('form input[type=file]')[0].files[0];
data.append('file',file);
data.append('sha256', sha256);
data.append('api_key', 'key');
console.log(file);
$.ajax({
url: '/report/ajax/upload_file/',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(data) {
$('#sandboxMessage').text(data.res);
$('#uploadResults').slideDown(300);
},
error: function(data) {
$('#customMessage').text('Sample upload failed');
$('#uploadResults').slideDown(300);
},
});
});
}
服务器端的python代码是
def upload_file(request):
sha256 = request.POST.get('sha256', None)
api_key = request.POST.get('api_key', None)
uploadFile = request.FILES['file']
headers = {'X-TOKEN-KEY': api_key}
res = requests.put(url='https://redacted.com/v1-1/file/'
+ sha256, headers=headers, data=uploadFile)
data = {
'sha256': sha256,
'api_key': api_key,
'res': json.loads(res.content)['message']
}
return JsonResponse(data)
最后,我的Nginx配置如下
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name redacted.com www.redacted.com;
rewrite ^ https://$server_name$request_uri? permanent;
}
server {
listen 443 ssl http2;
# Use only TLS
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
server_name redacted.com;
location /static/ {
root /var/www/redacted/;
}
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://unix:/var/www/redacted.sock$args;
}
# cert
ssl_prefer_server_ciphers on;
ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;
#Enable OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_session_cache shared:ssl:40m;
ssl_session_timeout 4h;
# Enable session tickets
ssl_session_tickets on;
ssl_certificate /etc/ssl/ssl-bundle.crt;
ssl_certificate_key /etc/ssl/redacted.key;
}