将文件从 iPhone 上传到 Django

发布于 2024-12-28 00:29:01 字数 2289 浏览 1 评论 0原文

抱歉,这是一个初学者的问题:我的 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>

现在,假设我想从我的 iPhone 应用程序发送一个简单的 txt 文件到服务器。 我真的不知道如何

  1. 提供文件名
  2. 指定enctype
  3. 确保它采用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 ...

Sorry, a beginner's question: I have a very simple function in my Django application with which I can upload a file from a web browser to my server (works perfectly!). Now, instead of the web browser, I would like to use an iPhone.

I got a bit stuck as I don't really know how to provide Django with a valid form, i.e. we need a file name and enctype="multipart/form-data" as far as I understand.

Here is my upload function in 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})

My template looks like this (upload.html):

<form action="" method="post" enctype="multipart/form-data">
    {{ form.file }}
    {{ form.non_field_errors }}
    <input type="submit" value="Upload" />
</form>

Now, let's suppose that I want to send a simple txt file from my iPhone app to the sever.
I don't really know how to:

  1. provide the file name
  2. specify the enctype and
  3. make sure that it's in a format Django can read

This is how far I got:

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];

However, Django will not except this as the form it expects is not valid. Cf. above:

form = UploadFileForm(request.POST, request.FILES)
if form.is_valid(): #this will not be true ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫罗兰の梦幻 2025-01-04 00:29:01

HTML 表单中的 enctype 应该是 HTTP 请求的 Content-Type。您当前正在将内容类型设置为'text/xml'

您还必须将主体构建为多部分哑剧对象。这个问题的答案似乎有一些代码: 文件上传到iPhone 编程中的 HTTP 服务器

由于您可以完全控制客户端,因此您的另一个选择是执行 HTTP PUT 请求。这实际上看起来更接近您对原始代码所做的事情。将方法更改为“PUT”,并且另一端不要使用 Django 表单;只需访问 request.raw_post_data 即可获取完整的文件数据。

The enctype from the HTML form should be the Content-Type of the HTTP request. You are currently setting the content type to 'text/xml' instead.

You will also have to build up the body as a multipart mime object. The answers to this question seem to have some code for that: File Upload to HTTP server in iphone programming

Your other option, since you have complete control of the client, is to do an HTTP PUT request. That actually looks closer to what you were doing with your original code. Change the method to 'PUT', and don't use a Django form on the other end; just access request.raw_post_data to get the complete file data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文