django —— KindEditor - 跨域上传图片

时间:2022-10-27 23:20:16
#跨域上传方法
def frontupload(request):
if request.method == 'POST':
item = {}
file = request.FILES.get('imgFile')
#定义跳转网址,就是前端伪造好的页面
callBackPath = 'http://localhost:8080/redirect.html'
f = open(os.path.join(UPLOAD_ROOT,'',file.name),'wb')
item['message'] = '上传成功'
item['url'] = 'http://localhost:8000/upload/'+ file.name
item['error'] = 0
#写文件 遍历图片文件流
for chunk in file.chunks():
f.write(chunk)
return HttpResponseRedirect(callBackPath + "?error=0&url="+item['url'])

其实页面有太大的区别   只是回调了一下

#回调页面  redirect.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>跨域重定向</title>
<script type="text/javascript">
function getParameter(val) {
var uri = decodeURI(window.location.search);
var re = new RegExp("" + val + "=([^&?]*)", "ig");
return ((uri.match(re)) ? (uri.match(re)[0].substr(val.length + 1)) : null);
} var upload_callback = function() {
var error = getParameter("error");
error = parseInt(error)
var dataObject;
if(error==0){
var url = getParameter("url");
dataObject = {"error": error, "url": url};
}else{
var message = getParameter("message");
dataObject = {"error": error, "message": message};
}
var data = JSON.stringify(dataObject)
document.getElementsByTagName("body")[0].innerHTML = '<pre>' + data + '</pre>';
}
</script>
</head>
<body onload="upload_callback();">
</body>
</html>
#kindEditor    index.html
            initKindEditor();
function initKindEditor() {
var kind = KindEditor.create('#my_reply_'+com_id+'', {
width: '80%', // 文本框宽度(可以百分比或像素)
height: '30%', // 文本框高度(只能像素)
minWidth: 400, // 最小宽度(数字)
minHeight: 100, // 最小高度(数字)
items : [ 'emoticons', 'image'],
uploadJson:'http://localhost:8000/md_admin/front_upload',
});
}
上传图片的话 必须有 uploadJson:'http://localhost:8000/md_admin/front_upload', 
后面的网址是你请求的网址
 
效果:
django —— KindEditor - 跨域上传图片