PHP文件上传到内存

时间:2009-10-16 19:52:20

标签: php file-upload

我想从html表单上传文件,将其发布到PHP并将其加载到内存中,绕过将其写入文件。是否可以进行文件上传并将其保存在内存中,还是必须将其写入文件?

6 个答案:

答案 0 :(得分:2)

我认为现在不可能。你不能使用带有enctype =“multipart / form-data”的php:// input,因此排除了从流中打开文件的麻烦。如果你去邮政路线,你只能使用$ _FILE变量,它不包含任何二进制数据,只是指向磁盘上文件的指针。

看起来xforms会提供帮助(http://www.ibm.com/developerworks/xml/library/x-xformstipuploadphp/index.html),但这甚至适用于Firefox 3.5。它需要一个插件,这对我来说是一个交易杀手。

答案 1 :(得分:2)

PUT选项很酷。如果你想使用POST和$ _FILES,我认为最接近的是将upload_tmp_dir指向ramdisk。

答案 2 :(得分:2)

我最近遇到了这个问题,最后使用以下解决方案: (不确定它是否真的解决了问题,我将非常感谢您的建议)

在客户端,

使用“Content-Type:application / octet-stream;”发送标头而不是“multipart / form-data”

因此上传文件不会保存到服务器上的临时目录中。

以ios objective-c代码为例:

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"your server address"]];
    [request setTimeoutInterval:30];
    [request setHTTPMethod:@"POST"];

    // set Content-Type in HTTP header
    NSString *contentType = [NSString stringWithFormat:@"application/octet-stream;"];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

    // post body
    NSMutableData *body = [NSMutableData data];

    //yourData is typed NSData here
    [body appendData:yourData]; 

    // setting the body of the post to the reqeust
    [request setHTTPBody:body];

    // set the content-length
    NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];


    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id result) {
            success(result);  
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id result){
        failure(error, result);
    }];
    [operation start];

在服务器端,

使用“php:// input”将文件检索为原始数据(请注意,php://输入不能用于“multipart / form-data”)

例如:$data = file_get_contents('php://input');

这里的$ data将是上传的文件。


在我们的例子中,文件上传频率非常高。因此最好将文件系统操作减少为可能的。

答案 3 :(得分:0)

由于PHP本身不处理实际的HTTP请求(这是Web服务器的工作),我无法想象这是可能的。如果有人能证明我错了,那真是太棒了。

答案 4 :(得分:0)

Http put在PHP中很容易。

<?php
$f = fopen('php://input','r');
$content ='';
while(!feof($f)){
    $content .= fread($f,8192);
}
?>

$ content是文件的内容。 请记住首先配置Web服务器以处理HTTP PUT请求。

答案 5 :(得分:0)

如果在linux下,您可以将上传目录指向 tmpfs 卷,即使使用文件系统界面,它也会在内存中。