nodeJS
を使用して、いくつかのヘッダー情報と多数のポイント(x、y、z)をサーバーにアップロードする必要があります(現在はlocalhost)。目的C - NodeJS - iOSアプリケーションからサーバーに特定のファイル(画像ではない)をアップロードする方法は?
- (IBAction)uploadFileButton:(id)sender {
NSLog(@"Going to upload file");
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:"http://localhost:3000/"]];
request.HTTPMethod = @"POST";
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:config];
//UIImagePNGRepresentation turns an instance of UIImage into PNG file data.
NSData* bytes = UIImagePNGRepresentation(self.imageView.image);//a random image displayed on my iOS view for testing purpose
NSURLSessionUploadTask* task = [session uploadTaskWithRequest:request fromData:bytes completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
if (error == nil && [(NSHTTPURLResponse*)response statusCode] < 300) {
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
}
}];
[task resume];
}
そしてサーバ側のため、このコード(単に面白い部分)を使用して:
今の私は、適切のiOS側のため、このコードを使用してPNGファイルをアップロードすることができますよ。
app.post('/',function(req,res){
//This looks up the value of the Content-Type header which is set by the mobile app.
var ctype = req.get("content-type");
//This tries to guess the file extension based upon the content type. For instance, an image/png should have a png extension.
var ext = ctype.substr(ctype.indexOf('/')+1);
if (ext) {ext = '.' + ext; } else {ext = '';}
//Create a filename by appending the appropriate extension to the new id.
var filename = "test" + ext;
console.log("filename : " + filename);
//The designated path to the file is in the server’s root directory, under the uploads sub-folder. __dirname is the Node.js value of the executing script’s directory.
filePath = __dirname + '/uploads/' + filename;
console.log("filepath : " + filePath);
var writable = fs.createWriteStream(filePath);
req.pipe(writable);
req.on('end', function(){
res.send(201, "ok");
});
writable.on('error', function(err) {
res.send(500,err);
console.log("Error uploading file.");
});
});
これまでのところ、いくつかの苦労の末、uploadsディレクトリにpngファイルをアップロードすることができました。
ここでは、特定の拡張子を持つ特定のファイルをアップロードしてさらに進めたいと考えています。
私は
[request addValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
に
[request addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
を変更しようとしましたが、私はNSDataの型に変換についてこだわっています。
私のサーバーにファイル(画像ではありません)をアップロードする方法を知っていますか?私はインターネットで検索しようとしましたが、関連する回答は見つかりませんでした。
しかし、私のファイルをjsonファイルに変換してからサーバーにアップロードする必要があるのでしょうか? (私はjsonファイルをアップロードする方が簡単だと思う)
私を助けてくれますか?
ご協力いただきありがとうございます。
EDIT:AFNetworkingで試しても、私は次のコードでライブラリAFNetworkingと試みたが、それは働いていない
を働いていません。私は間違いがない。
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURL *URL = [NSURL URLWithString:"http://localhost:3000/"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *data = @"Model.pcd";
NSString *data_path = [documentsDirectoryPath stringByAppendingPathComponent:data];
NSLog(@"path: %@ ", data_path);
NSURL *filePath = [NSURL fileURLWithPath:data_path];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(@"[INFO] Error: %@", error);
} else {
NSLog(@"[INFO]Upload successfully : %@ %@", response, responseObject);
}
}];
[uploadTask resume];
まず私は、次のエラーでした:
NSLocalizedDescription=Request failed: unacceptable content-type: text/html
をしかしmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
を追加することによって、私はすべてのエラーを持っていません。
NSHTTPURLResponse: 0x6180002310a0> { URL: http://localhost:3000/ } { status code: 200, headers {
"Accept-Ranges" = bytes;
"Cache-Control" = "public, max-age=0";
Connection = "keep-alive";
"Content-Length" = 233;
"Content-Type" = "text/html; charset=UTF-8";
Date = "Thu, 13 Oct 2016 12:03:58 GMT";
Etag = "\"233-1476189758000\"";
"Last-Modified" = "Tue, 11 Oct 2016 12:42:38 GMT";
"X-Powered-By" = Express;
} } <3c666f72 6d206964 20202020 20202020 3d202022 75706c6f 6164466f 726d220a 20202020 20656e63 74797065 2020203d 2020226d 756c7469 70617274 2f666f72 6d2d6461 7461220a 20202020 20616374 696f6e20 2020203d 2020222f 6170692f 70686f74 6f220a20 20202020 6d657468 6f642020 20203d20 2022706f 7374220a 3e0a3c69 6e707574 20747970 653d2266 696c6522 206e616d 653d2275 73657250 686f746f 22202f3e 0a3c696e 70757420 74797065 3d227375 626d6974 22207661 6c75653d 2255706c 6f616420 496d6167 6522206e 616d653d 22737562 6d697422 3e0a3c2f 666f726d 3e>
アップロードコードを変更する必要があります。 – vaibhav
解決策ではありませんが、ブロック内でデバッグに役立てることができます: 'if([responseObject isKindOfClass:[NSData class]]){NSLog(@" responseObject:%@ "、[NSString alloc] initWithData:responseObject encoding :NSUTF8StringEncoding];} '役に立たないNSDataを印刷するのではなく;) – Larme