我正在尝试使用 ASIFormDataRequest 从 iphone 将图像上传到 django。
在我的 django views.py
class UploadFileForm(forms.Form):
name = forms.CharField(max_length=255)
file = forms.FileField()
@csrf_exempt
def upload_image(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid(): ##this is always fail
newimage = Image(imgfile = request.FILES['image'])
newimage.save()
return HttpResponse('succeeded')
else:
return HttpResponse('failed')
在模型.py
class Image(models.Model):
imgfile = models.FileField(upload_to='images/')
我在settings.py中得到了这个
MEDIA_ROOT = '/srv/www/media'
使用上面的代码,我无法验证表单,但如果我删除 form.is_valid(),则图像成功上传到 /srv/www/media/images/
以下是iOS代码:
formRequest = [ASIFormDataRequest requestWithURL:url];
[formRequest setPostFormat:ASIMultipartFormDataPostFormat];
formRequest.delegate = self;
[formRequest setData:UIImageJPEGRepresentation(image, 1.0f) withFileName:fileName andContentType:@"image/jpeg" forKey:@"image"];
[formRequest setPostValue:userName forKey:@"name"];
[formRequest setRequestMethod:@"POST"];
[formRequest setPostFormat:ASIMultipartFormDataPostFormat];
[formRequest startAsynchronous];
拜托,欢迎和赞赏任何建议。