专业的编程技术博客社区

网站首页 > 博客文章 正文

Unity3D 上传图片到 NodeJS Server

baijin 2024-09-09 01:03:08 博客文章 17 ℃ 0 评论

客户端Unity3D 如何上传图片到NodeJS 开发的服务器。网上搜了下,资源很少。

Unity部分代码:

参数 imageFile为要上传的图片本地路径,callback为上传后的回调

 IEnumerator UploadImage(string imageFile,Action<int,string> callback) 
 {
 byte[] levelData = File.ReadAllBytes(imageFile);
 WWWForm form = new WWWForm();
 form.AddBinaryData ( "upfile", levelData, "test.png","image/png");
 WWW w = new WWW(URL_SERVER,form);
 yield return w;
 if (!string.IsNullOrEmpty(w.error))
 {
 Debug.LogError( w.error ); 
 callback(-1,w.error);
 }
 else
 {
 Debug.Log(w.text);
 callback(0,w.text);
 }
 }

NodeJS部分使用的 express-fileupload 直接npm安装

npm install --save express-fileupload

创建 app.js ,复制下面的代码进去

var express = require('express');
var app = express();
var upload = require('express-fileupload');
var path = require("path");
app.use(upload());
app.post('/upload',function(req,res){
 console.log(req.files);
 if(req.files.upfile){
 var file = req.files.upfile,name = file.name,type = file.mimetype;
 var uploadpath = __dirname + '/uploads/' + file.md5;
 file.mv(uploadpath,function(err){
 if(err){
 console.log("File Upload Failed",name,err);
 res.send("Error Occured!")
 }
 else {
 console.log("File Uploaded",name);
 res.send("success");
 }
 });
 }
 else {
 res.send("No File selected !");
 res.end();
 };
});

然后 执行命令 node app.js, Unity执行上传后,便会在uploads目录下出现上传的图片,这里使用文件的md5做文件名。

如果需要下载文件

app.get('/download/*', function (req, res, next) {
 var f = req.params[0];
 f = path.resolve(f);
 console.log('Download file: %s', f);
 res.download(f);
});

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表