客戶端Unity3D 如何上傳圖片到NodeJS 開發的服務器。網上搜了下,資源很少。
Unity部分代碼:
參數 imageFile為要上傳的圖片本地路徑,callback為上傳後的回調
IEnumerator UploadImage(string imageFile,Actioncallback)
{
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做文件名。
![Unity3D 上傳圖片到 NodeJS Server](http://p2.ttnews.xyz/loading.gif)
如果需要下載文件
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);
});
閱讀更多 UnityAsk 的文章