如何不使用表单就将文件保存在数据库中。
models.py
class mymodel(models.Model):
myfile = models.FileField(upload_to='folder/', blank=True, null=True)
ajax和html
<input id="id_video" type="file">
<button onclick="upload_video()">save</button>
function upload_video(){
var formData = new FormData();
formData.append('file', $('#id_video')[0].files[0]);
console.log(formData)
$.ajax({
type:'GET', url : '/upload-video/',
async: true,
data:formData,,
contentType: false,
processData: false,
success : function(data){
alert(data)
}
})
}
views.py
def upload_videos(request):
video_file = request.GET.get('formData')
# how to save
video_file.save()
return Httpresponse('saved')
答案 0 :(得分:2)
GET
方法不能传输任何内容数据,因此您需要使用POST
方法:
$.ajax({
type: 'POST',
...
}
现在,在view
中,您可以从request.FILES
获取类似文件的对象:
def upload_videos(request):
video_file = request.FILES['file']
# Create model record
_ = mymodel.objects.create(myfile=video_file.getvalue())
return Httpresponse('saved')
OTOH,如果您收到data
作为POST
参数,则可以使用io.BytesIO
获取类似文件的对象,并使用它来创建模型记录:
import io
def upload_videos(request):
try:
video_file = request.FILES['file']
except KeyError:
# You can catch KeyError here as well
# and return a response with 400 status code
try:
video_file_data = request.POST['data']
except KeyError:
return Httpresponse('No file content', status=400)
video_file = io.BytesIO(video_file_data)
# Create model record
_ = mymodel.objects.create(myfile=video_file.getvalue())
else:
# Create model record
_ = mymodel.objects.create(myfile=video_file.getvalue())
return Httpresponse('saved')
FWIW,您应该将模型类命名为 CamelCase 。
以上是执行此操作的基本思想,您可以增强此思想以满足您的需求。