将大型NSData上传到Web [英] Uploading Large NSData to the Web

查看:90
本文介绍了将大型NSData上传到Web的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个必须将大文件(主要是电影/视频)上传到网络的应用程序。在阅读了我的内容之后,我采用了将电影转换为NSData的方法,然后将其包含为 NSURLConnection的 HTTPBody 。但是,在将电影(原来是 ALAsset )转换为 NSData 时,我会收到内存警告,然后是随后的崩溃。

I'm currently working on an application that has to upload large files (mainly movies/videos) to the web. After reading what I can, I went the the approach of converting the movie to NSData and then including that as the NSURLConnection's HTTPBody. However, upon converting the movie (which was originally an ALAsset) into NSData, I receive a memory warning and then a subsequent crash.

我不知道如何上传这些类型的大文件,如果这些数据只会导致即时崩溃。我想到的一个解决方案是写入文件系统,然后直接从那里上传文件,但我无法找到有关如何实现此目的的任何信息。

I have no idea how I would go about uploading these types of large files, if that data just causes an instant crash. One solution that I was thinking of is writing to the filesystem and then uploading a file directly from there, but I have not been able to find any information on how one would accomplish this.

这是我使用的相关代码。如果有什么我在这里做错了,我很想知道。

Here is the relevant code that I use. If there is something that I'm doing wrong right here, I'd love to know.

ALAssetRepresentation *representation = [asset defaultRepresentation];

Byte *buffer = (Byte *)malloc([representation size]);
NSUInteger buffered = [representation getBytes:buffer fromOffset:0.0 length:[representation size] error:nil];

uploadData = [NSData dataWithBytes:buffer length:buffered];

free(buffer);


推荐答案

假设上传电影是有意义的原生格式,你可以使用BSD(即Unix)第3节界面轻松实现这一点:

Assuming that it makes sense to upload the movie in its native format, you can really make this easier using the BSD (ie Unix) section 3 interface:


  • 给定一个filePath,打开该文件并获取一个int文件描述符(fd)

  • given a filePath, open the file and get an int file descriptor (fd)

使用fd,获取文件的长度

with fd, get the length of the file

跟踪您已加载了多少,以便知道从何处获取更多数据

keep track of how much you've loaded so you know where to get more data

使用mmap(3)在JUST中进行映射您要随时上传的数据,并在发送数据时使用mmap返回的void *指针作为数据的位置

use mmap(3) to map in JUST the data you want to upload at any time, and use the void * pointer returned by mmap as the location of the data

发送完所有数据后,将旧数据块和mmap一个新数据块映射

when the data has been sent, munmap the old data chunk and mmap a new chunk

,将最后一个数据块,即关闭(fd)进行munmap。

after all data is sent, munmap the last chunk, the close(fd).

没有临时内存 - 没有mallocs。每当我必须处理大文件时,我都会使用mmap。

No temporary memory - no mallocs. I use mmap whenever I have to deal with huge files.

编辑:您还可以使用NSData dataWithContentsOfFile:选项设置为使用mmap的选项。然后,您将使用字节指针在需要时读取小块。

you can also use NSData dataWithContentsOfFile:options with options set to use mmap. You would then use the byte pointer to read small chunks as you need them.

这篇关于将大型NSData上传到Web的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆