gpt4 book ai didi

php - NSURLSessionUploadTask 上传文件失败

转载 作者:可可西里 更新时间:2023-11-01 03:34:58 30 4
gpt4 key购买 nike

下面是上传图像文件的片段。我只想使用 NSURLSessionUploadTask,因为它提供了我想在我的应用程序中使用的后台上传功能。

此外,我还想在上传文件时发送参数。

此外,我不擅长服务器端代码。任何人都可以指导我我做错了什么。

上传代码

NSString* filePath = [[NSBundle mainBundle]
pathForResource:@"sample" ofType:@"jpg"];
uint64_t bytesTotalForThisFile = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileSize];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadPath];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%llu", bytesTotalForThisFile] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];

[request setTimeoutInterval:30];

NSString* filePath = [[NSBundle mainBundle]
pathForResource:@"sample" ofType:@"jpg"];


NSURLSessionUploadTask *taskUpload= [self.uploadSession uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:filePath]];

PHP 代码

<?php

$objFile = & $_FILES["file"];
$strPath = basename( $objFile["name"] );

if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) {
print "The file " . $strPath . " has been uploaded.";
} else {
print "There was an error uploading the file, please try again!";
}

从服务器端我得到 $_FILES 的空数组

最佳答案

我将放一个代码示例。检查您是否在控制台上收到任何错误。

// 1. config
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

// 2. if necessary set your Authorization HTTP (example api)
// [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}];

// 3. Finally, you create the NSURLSession using the above configuration.
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// 4. Set your Request URL
NSURL *url = <yourURL>;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

// 5. Set your HTTPMethod POST or PUT
[request setHTTPMethod:@"PUT"];

// 6. Encapsulate your file (supposse an image)
UIImage *image = [UIImage imageNamed:@"imageName"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

// 7. You could try use uploadTaskWithRequest fromData
NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
if (!error && httpResp.statusCode == 200) {

// Uploaded

} else {

// alert for error saving / updating note
NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode);
}
}];

关于php - NSURLSessionUploadTask 上传文件失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31130721/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com