1.首先用axios发送文件
let formData = new FormData()//创建表单对学校 formData.append('name', object.name)//与表单一起提交的其他数据 if(object.img && object.img.length>0) { formData.append('img', object.img[0].file)//文件数据,必须是File对象 } this.$axios({ method: 'post', url: 'catagory/', data: formData, headers: { 'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime() } }) .then( res => { console.log('上传成功!') } ) .catch( err => { console.log(err) console.log('上传失败!') } )
2.django的ImageField需要接收InMemoryUploadedFile对象,所以先写一个方法把前端文件对象转换为所需对象
from django.core.cache import cache
def toInMemoryUploadedFile(self,requestfile): image = requestfile image_data = [image.file, image.field_name, image.name, image.content_type, image.size, image.charset, image.content_type_extra] cache_key = 'image_key' cache.set(cache_key, image_data, 60) cache_data = cache.get(cache_key) image = InMemoryUploadedFile(*cache_data) return image
3.最后在代码中使用上述方法转换文件对象后,再放回request中供django使用就可以了
def post(self, request, *args, **kwargs): request.data['img'] = self.toInMemoryUploadedFile(request.data['img'])//放回request request.data['sort_id'] = int(round(time.time() * 1000)) return self.create(request, *args, **kwargs)
ps.从后台获取图片时需配置url文件
from django.conf.urls.static import static from django.conf import settings urlpatterns = [ ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
把文件存本地需配置settings文件
MEDIA_ROOT = 'media/' MEDIA_URL = 'media/'