关于图片保存的问题,纠结了好久急求大神解答。。。
发布于 8个月前 作者 zikong 726 次浏览

我想用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,也就是获取不到上传的文件。求帮帮忙!!!

5 回复

你有加bodyparser或者formidable之类的中间件吗 ps lz好厉害啊,移动开发前后端通吃啊

req.files是undefined肯定是因为你没有安装中间件。没捕获post请求

我已经加了bodyparser中间件,捕获post请求是什么意思

app.use(express.multipart({keepExtensions: true, uploadDir: 'your_upload_path’})); 这是我express 3 的一个node.js的一段上传用得代码,楼主在app.js中是怎么配置的?

3楼正解,express 4.x以后我都是用的 connect-multiparty 中间件了来获取 req.files 了。

回到顶部