使用用户凭据上传目标c多部分表单文件

时间:2016-07-16 06:28:40

标签: objective-c node.js upload multipartform-data formidable

我在目标C中有以下代码,可以通过POST将文件上传到node.js / formidable。

但我想在此POST请求中包含用户凭据和有关该文件的其他详细信息。我看了一遍,找不到一个可以让我实现这个目标的例子。

请建议我为实现上述目标需要做些什么。

这是我在Objective C中的代码:

-(void) uploadToServer:(NSData*) mediaData
                         asType:(int) mediaType
                         asFile:(NSString*) saveFileAs{

    NSDictionary *params = @{@"subFolder"   : G_deviceName,
                             @"filename"    : saveFileAs
                             };

    NSString *boundary = [self generateBoundaryString];


        // configure the request

    NSString * urlForUploading = [NSString stringWithFormat:@"%@/upload",G_appServerURL ];

    NSURL *uploadToURL = [NSURL URLWithString:urlForUploading];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadToURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    [request setHTTPMethod:@"POST"];

        // set content type

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

        // create body

    NSData *httpBody = [self createBodyWithBoundary:boundary parameters:params mediaData:mediaData fieldName:@"fieldName"];

    self.session = [NSURLSession sharedSession];  // use sharedSession or create your own

    NSURLSessionTask *task = [self.session uploadTaskWithRequest:request fromData:httpBody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"error = %@", error);
            [[NSNotificationCenter defaultCenter] postNotificationName:@"activeUpload" object:nil userInfo:nil];
            return;
        }
        else{
            NSLog(@"uploadToServer successful." );

            [[NSNotificationCenter defaultCenter] postNotificationName:@"activeUpload" object:nil userInfo:nil];
        }

        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"result = %@", result);
    }];
    [task resume];

}

- (NSData *)createBodyWithBoundary:(NSString *)boundary
                        parameters:(NSDictionary *)parameters
                         mediaData:(NSData*)mediaData
                         fieldName:(NSString *)fieldName
{
    NSMutableData *httpBody = [NSMutableData data];

        // add params (all params are strings)

    [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) {
        [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]];
        [httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]];
    }];

        // add image data

    NSString *formName = [parameters objectForKey:@"subFolder"];
    NSString *filename  = [parameters objectForKey:@"filename"];
    NSString *mimetype  = @"image/jpeg";  //[self mimeTypeForPath:path];

    [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", formName, filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", mimetype] dataUsingEncoding:NSUTF8StringEncoding]];
    [httpBody appendData:mediaData];
    [httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [httpBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    return httpBody;
}

- (NSString *)generateBoundaryString
{
    return [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]];

}

以下是node.js Server中的代码,它接收此POST请求并保存文件:

app.post('/ upload',function(req,res){

  var subFolder;

  // create an incoming form object
  var form = new formidable.IncomingForm();

  form.multiples = false;

  form.uploadDir = '/home/uploads'

  form.on('fileBegin', function(name, file) {

    console.log('entered fileBegin ... ');
      form.uploadDir = form.uploadDir + name;

  });

  // every time a file has been uploaded successfully, rename it to it's orignal name
  form.on('file', function(field, file) {
    fs.rename(file.path, path.join(form.uploadDir, file.name));

  });


    form.parse(req, function(err, fields, files) {
        if (err) 
          console.log("In form.parse, error occured : " + util.inspect(err));

        console.log("parsing form now...");

    });

  // log any errors that occur
  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
        console.log('File uploaded to location : ' + form.uploadDir);
    res.end('success');
  });


});

1 个答案:

答案 0 :(得分:1)

我猜form.parse提供了那些额外的参数

 form.parse(req, function(err, fields, files) {
   console.log("parsing form now..."+ JSON.stringify(fields));
 });

如果您之前仍想要,请检查此

 form.on('field', function(name, value) { }); 

如果也迟到,那么尝试从HTML表单重新排序序列