我正在使用jquery fileupload和django项目。我想在我的fileupload表单中添加一个额外的字段。我关注了this文档。但是,当我尝试上传图像时出现forbidden
错误,django的控制台错误是:
[14/Apr/2015 09:40:37]"POST /upload/ HTTP/1.1" 403 2274
我的脚本如下:
$(document).ready(function() {
$('form#fileupload').bind('fileuploadsubmit', function (e, data) {
var name = $('form#{{ opts.model_name }}_form').find('input[name="name"]').val();
$('form#fileupload').find('input[name="image_name"]').val( name );
data.formData = { 'image_name': name };
if (!data.formData.image_name) {
data.context.find('button').prop('disabled', false);
return false;
}
});
});
我的要求是:
Remote Address:127.0.0.1:8000
Request URL:http://localhost:8000/upload/
Request Method:POST
Status Code:403 FORBIDDEN
Response Headers
view source
Content-Type:text/html
Date:Tue, 14 Apr 2015 08:40:37 GMT
Server:WSGIServer/0.1 Python/2.7.8
X-Frame-Options:SAMEORIGIN
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8,es-419;q=0.6,es;q=0.4,pt;q=0.2,ko;q=0.2,gl;q=0.2
Connection:keep-alive
Content-Length:29144
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryURf6WD0fBem7roLF
Cookie:PHPSESSID=fqdqkmd9cmb3oi2odcd6ogiru7; _osra_session=TUNTZWJaWmJXRitBeFJuV1JRQm9BSEVvUklia3RtN1ZOK3NzUVNqcEpYcmlCeVhDWHE4K0JmdjF1RlkzODVmLzg2cTUreE1oQnp6Z0JKU3d4aGtHYmkyS0MzQVRQc1VYMDQ5WWFGYk56RGQxNDQxcmV5S1pJd0VvS0Mxc2MzS1laMkwwZlI0NFBDcDdsRDZPMW1mT0JyRUNaSXMyODdZcklCVFNsaER0RmdUM0xzbFRJMk9RSkZvSFRXUXNCc3hvNy9wMDhGb0o4M3hZdW1iWFFZTGdXU3RNTHFGQnNaVkpGTkwrY2IzdWRZQWJLeWt1VGR3cy94ZnRWRGVOTldlakF2Zm1xUFZGSnRxSXpkUU4rNWVWbHc9PS0tZTh2c3U5cjZmN1p6eDB6ZFNuTFN6QT09--2880fbb1b8182485ef09f12b95fd3e7c6d71a714; sessionid=asmv53nr7qc4f1ra930ux7zp29k0vdks; csrftoken=cqqQDJsMROiJa5AtzxVJshOYK49Hl2WL
Host:localhost:8000
Origin:http://localhost:8000
Referer:http://localhost:8000/admin/imageboard/image/add/
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
------WebKitFormBoundaryURf6WD0fBem7roLF
Content-Disposition: form-data; name="image_name"
asd
------WebKitFormBoundaryURf6WD0fBem7roLF
Content-Disposition: form-data; name="files[]"; filename="4f9.jpg"
Content-Type: image/jpeg
------WebKitFormBoundaryURf6WD0fBem7roLF--
asd 是我尝试发送的名称。
如果我没有在表单中添加任何其他数据,我的示例会有效。
可能是什么问题?
修改 - 解决了
我按照这两个帖子解决了我的问题:
我使用jQuery Cookie方法。我发现它更容易实现;)。
然后在我的javascript中添加了:
var csrftoken = $.cookie('csrftoken');
console.log(csrftoken);
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}