django 的 ajax 方式上传图片
页面代码:
<html>
<!-- 引入相关的js文件,相对路径 -->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajaxfileupload.js"></script>
<!-- 执行上传文件操作的函数 -->
<script type="text/javascript">
function ajaxFileUpload(){
$.ajaxFileUpload(
{
url:'update.do?method=uploader', //需要链接到服务器地址
secureuri:false,
data: {
'csrfmiddlewaretoken': getCookie('csrftoken')
},
fileElementId:'houseMaps', //文件选择框的id属性
dataType: 'xml', //服务器返回的格式,可以是json
success: function (data, status) //相当于java中try语句块的用法
{
$('#result').html('添加成功');
},
error: function (data, status, e) //相当于java中catch语句块的用法
{
$('#result').html('添加失败');
}
}
);
}
</script>
</head>
<body>
<form method="post" action="update.do?method=uploader" enctype="multipart/form-data">
<input type="file" id="houseMaps" name="houseMaps"/>
<input type="button" value="提交" onclick="ajaxFileUpload()"/>
</form>
<div id="result"></div>
</body>
</html>
服务器端代码:
from django.core.files.uploadedfile import UploadedFile
class UploadFiles(View):
def post(self,request,type):
file = request.FILES.values()[0]
wrapped_file = UploadedFile(file)
upload = UploadNeed.objects.create(type= type, storage=wrapped_file)
upload.save()
msg = {'state': True, 'msg': u'上传成功'}
return HttpResponse(simplejson.dumps(msg))