抱歉,初学者的问题:我的 Django 应用程序中有一个非常简单的功能,我可以使用它从 Web 浏览器将文件上传到我的服务器(完美运行!)。现在,我想使用 iPhone,而不是网络浏览器。
我有点卡住了,因为我真的不知道如何为 Django 提供有效的表单,即据我所知,我们需要一个文件名和 enctype="multipart/form-data"。
这是我在 Django 中的上传功能:
class UploadFileForm(forms.Form):
file = forms.FileField()
def handle_uploaded_file(f):
destination = open('uploads/example.txt', 'wb+')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
def upload_file(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['file'])
print form
print request.FILES
return HttpResponse('Upload Successful')
else:
form = UploadFileForm()
return render_to_response('upload.html', {'form': form})
我的模板看起来像这样(upload.html):
<form action="" method="post" enctype="multipart/form-data">
{{ form.file }}
{{ form.non_field_errors }}
<input type="submit" value="Upload" />
</form>
现在,假设我想将一个简单的 txt 文件从我的 iPhone 应用程序发送到服务器。 我真的不知道如何:
- 提供文件名
- 指定
enctype
和 - 确保它是 Django 可以读取的格式
这是我走了多远:
NSString *fileContents = [self loadTXTFromDisk:@"example.txt"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL
URLWithString:@"http://127.0.0.1:8000/uploadfile/"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/xml" forHTTPHeaderField:@"Content-type"];
[request setValue:[NSString stringWithFormat:@"%d", [fileContents length]]
forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[fileContents dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self];
但是,Django 不会例外,因为它期望的形式是无效的。参照。以上:
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid(): #this will not be true ...