UIImage to NSData Return Null

时间:2016-09-09 17:41:42

标签: ios objective-c uiimage base64 nsdata

我想将几个.png图像放入由mongodb支持的数据库中:

SELECT CASE 
         WHEN cd_id = '999999' THEN Cast(cd_seq_no AS VARCHAR(50)) + '999.99' 
         ELSE Cast(cl_id AS VARCHAR(50))+Cast(cd_seq_no AS VARCHAR(50))+Cast(cd_id AS VARCHAR(50))
       END 
FROM   yourtable 

然后我将图像数据附加到http正文数据:

// Image data array
NSMutableArray *allImgData = [[NSMutableArray alloc] init];
for (UIButton *photoButton in self.photoButtons) {
    UIImage *buttonImage = [photoButton imageForState:UIControlStateNormal];
    NSData *imgData = UIImagePNGRepresentation(buttonImage);
    // add to image data array for upload
    [allImgData addObject:imgData];
}

当我尝试将保存在数据库中的图像数据转换回UIImage时,它始终为空:

// Append image data to body
NSMutableData *bodyData = [NSMutableData data];
int i = 1;
for (NSData *imgData in allImgData) {
    [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@%d.png\"\r\n", fileParamConstant, i] dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:imgData];
    [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    i++;
}
// Append one last boundary
[bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:bodyData];

我认为数据看起来是正确的,但为什么图像没有以正确的方式解释?

更新

目标C部分:

        if (photo1 && photo1.count != 0) {
                    NSData *data = [photo1[0] dataUsingEncoding:NSUTF8StringEncoding];
                    NSLog(@"Data is here: %@", data);
                    // Data is here: <efbfbd50 4e470d0a 1a0a0000 000d4948 0000efbf bd000000 28000000 efbfbd00 0000efbf ...

                    UIImage *photo1Image = [UIImage imageWithData:data];
                    NSLog(@"Image is here: %@", photo1Image);
                    // Image is here: (null)

                    [self.photo1Button setImage:photo1Image forState:UIControlStateNormal];
                }

}

Node.js Part:

- (void) uploadPhotoData {
// NSURLSession Submit/Resubmit data
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
// NSURL
NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:@"LoginUserName"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"http://localhost:8080/api/users/competitorProductPhotoData/%@", userName]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
// "Put" method
// Request setup
// [urlRequest setHTTPMethod:@"PUT"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest addValue:@"image/png" forHTTPHeaderField:@"Content-Type"];
//    [urlRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
//    [urlRequest setHTTPShouldHandleCookies:NO];
//    [urlRequest setTimeoutInterval:3000];
// Set boundary and content type (boundary is a random String)
NSString *boundaryConstant = [NSString stringWithFormat:@"---------------------------14737809831464368775746641449"];
NSString* fileParamConstant = @"photo";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryConstant];
[urlRequest setValue:contentType forHTTPHeaderField: @"Content-Type"];
// Image data array
NSMutableArray *allImgData = [[NSMutableArray alloc] init];
for (UIButton *photoButton in self.photoButtons) {
    UIImage *buttonImage = [photoButton imageForState:UIControlStateNormal];
    NSData *imgData = UIImagePNGRepresentation(buttonImage);
    // NSString *imgString = [UIImagePNGRepresentation(buttonImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    // add to image data array for upload
    [allImgData addObject:imgData];
}
// Append image data to body data
NSMutableData *bodyData = [NSMutableData data];
int i = 1;
for (NSData *imgData in allImgData) {
    [bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"%@%d.png\"\r\n", fileParamConstant, i] dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:imgData];
    [bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    i++;
}
// Append one last boundary
[bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[urlRequest setHTTPBody:bodyData];
// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[bodyData length]];
[urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
// Start session task
NSURLSessionUploadTask* task = [session uploadTaskWithRequest:urlRequest fromData:bodyData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error == nil && [(NSHTTPURLResponse*)response statusCode] < 300) {
        if (error == nil) {
            NSLog(@"Successfully submitted photo data. No error.");
        } else {
            NSLog(@"Photo data Error: %@", [error localizedDescription]);
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.submitImageButton.image = [UIImage imageNamed:@"WrongUser"];
            }];
        }
    }
}];
[task resume];

架构:

// on routes that end in /users/competitorProductPhotoData
// ----------------------------------------------------
router.route('/users/competitorProductPhotoData/:userName')

// update the user info (accessed at PUT     http://localhost:8080/api/users/competitorAnalysisPhotoData)
.post(function(req, res) {

    // Parse Multipart-data form upload
    var form = new multiparty.Form();

    // Errors may be emitted
    // Note that if you are listening to 'part' events, the same error may be
    // emitted from the `form` and the `part`.
    form.on('error', function(err) {
        console.log('Error parsing form: ' + err.stack);
    });

    form.on('file', function(err, files) {
        fs.readFile(files.path, function (err, data) {
            if (err) {
                console.log('Error reading file path: ' + err.stack);
            }

            // Upload photo to the embedded document
            if (files.originalFilename === 'photo1.png') {
                User.findOneAndUpdate(
                    { userName : req.params.userName},
                    { $set:
                        { "competitorProductPhoto.0.photo1" : data }
                    },
                    { upsert : true },
                    function(err, user) {
                        // After mongodb is done updating, you are receiving the updated file as callback

                        // Now you can send the error or updated file to client
                        if (err)
                            return res.send(err);
                        return;
                    });
            } else if (files.originalFilename === 'photo2.png') {
                User.findOneAndUpdate(
                    { userName : req.params.userName},
                    { $set:
                        { "competitorProductPhoto.0.photo2" : data }
                    },
                    { upsert : true },
                    function(err, user) {
                        // After mongodb is done updating, you are receiving the updated file as callback

                        // Now you can send the error or updated file to client
                        if (err)
                            return res.send(err);
                        return;
                    });
            } else if (files.originalFilename === 'photo3.png') {
                User.findOneAndUpdate(
                    { userName : req.params.userName},
                    { $set:
                        { "competitorProductPhoto.0.photo3" : data }
                    },
                    { upsert : true },
                    function(err, user) {
                        // After mongodb is done updating, you are receiving the updated file as callback

                        // Now you can send the error or updated file to client
                        if (err)
                            return res.send(err);
                        return;
                    });
            } else if (files.originalFilename === 'photo4.png') {
                User.findOneAndUpdate(
                    { userName : req.params.userName},
                    { $set:
                        { "competitorProductPhoto.0.photo4" : data }
                    },
                    { upsert : true },
                    function(err, user) {
                        // After mongodb is done updating, you are receiving the updated file as callback

                        // Now you can send the error or updated file to client
                        if (err)
                            return res.send(err);
                        return;
                    });
            }
        });
    });

    // form.parse(req);
    form.parse(req);
})

0 个答案:

没有答案