我想用Node实现图片文件的存储,然后通过IOS客户端上传。在网上找了好久,一直没能解决问题
app.post('/avatar', function(req, res) {
console.log(req);
if(!(req.query.username)) {
return res.json({
code: 0,
msg: '参数信息不完整'
});
}
// 获得文件的临时路径
var tmp_path = req.files.file.path;
console.log(tmp_path);
// 指定文件上传后的目录 - 示例为"avatars"目录。
var target_path = '../avatars/' + req.files.file.name;
// 移动文件
fs.rename(tmp_path, target_path, function(err) {
if (err) {
return res.json({
code: 0,
msg: err.toString()
});
}
// 删除临时文件夹文件,
fs.unlink(tmp_path, function(err) {
if (err) throw err;
});
});
});
ios客户端上传代码如下
NSString *username = [ZKConstValue getLoginStatus];
if (!username && [username isEqualToString:@""]) {
NSLog(@"ERROR: postImage,username is valide");
return;
}
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/avatar_%@.png", username]];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:pngPath atomically:YES];
MKNetworkEngine *networkEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_WITHOUT_HTTP];
MKNetworkOperation *networkOperation = [networkEngine operationWithPath:[NSString stringWithFormat:@"avatar?username=%@", username] params:nil httpMethod:@"POST"];
[networkOperation addFile:pngPath forKey:@"file" mimeType:@"image/png"];
[networkOperation setFreezable:YES];
[networkOperation addCompletionHandler:^(MKNetworkOperation *completedOperation) {
NSString *responseString = [completedOperation responseString];
NSLog(@"server response: %@",responseString);
} errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
NSLog(@"Upload avatar error: %@", error);
}];
[networkEngine enqueueOperation:networkOperation];
Request
-------
curl -X POST "http://192.168.0.100:1337/avatar?username=dbngb" -F "file=@/var/mobile/Containers/Data/Application/1B756503-C0BC-4A36-8C76-480EE8111C1D/Documents/avatar_dbngb.png;type=image/png"
--------
这样上传后在服务端打印req.files是undefine,也就是获取不到上传的文件。求帮帮忙!!!