Unity 上传下载随笔

Unity + NodeJs 上传下载文件 随笔(还木有实现完整)

安装node.js node -v
1.npm install connect serve-static 安装
2.npm install express -g
3.npm install mysql -g
开发环境搭建 sublime3 + nodejs 插件
4.安装package control 并在package control 安装nodejs 插件

JS代码如下:只做了接受 并没有做处理(不太会)

var express = require('express')
var multer  = require('multer')
var upload = multer()

var documentRoot = 'E:/webTest/www';
var app = express();
app.use(express.static(documentRoot));
app.listen(8888);

app.post('/file-upload', upload.array('file',100), function (req, res, next) {
    console.log(req.files);
    res.send('文件上传成功');
    console.log('Upload success');

})

console.log('Server start success !!');

Unity C#代码 (代码略显浮夸,请轻吐槽)

    public static IEnumerator UpLoad(string desFileName, string url)
    {
        string url1 = url;
        if (File.Exists(desFileName))
        {
            byte[] bytes = File.ReadAllBytes(desFileName);

            List<IMultipartFormSection> form = new List<IMultipartFormSection>();
            form.Add(new MultipartFormFileSection("file", bytes, "3_2.jpg", "image/jpg"));
            form.Add(new MultipartFormFileSection("file", bytes, "3_2_2.jpg", "image/jpg"));

            byte[] boundary = UnityWebRequest.GenerateBoundary();
            //serialize form fields into byte[] => requires a bounday to put in between fields
            byte[] formSections = UnityWebRequest.SerializeFormSections(form, boundary);
            byte[] terminate = Encoding.UTF8.GetBytes(String.Concat("\r\n--", Encoding.UTF8.GetString(boundary), "--"));
            // Make my complete body from the two byte arrays
            byte[] body = new byte[formSections.Length + terminate.Length];
            Buffer.BlockCopy(formSections, 0, body, 0, formSections.Length);
            Buffer.BlockCopy(terminate, 0, body, formSections.Length, terminate.Length);
            // Set the content type - NO QUOTES around the boundary
            string contentType = String.Concat("multipart/form-data; boundary=", Encoding.UTF8.GetString(boundary));

            using (UnityWebRequest www = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST))
            {
                UploadHandlerRaw uploadHandlerFile = new UploadHandlerRaw(body);
                www.uploadHandler = (UploadHandler) uploadHandlerFile;
                www.uploadHandler.contentType = contentType;
                www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
//              www.SetRequestHeader("Content-Type", "multipart/form-data");
                yield return www.Send();
                if (www.isNetworkError || www.isHttpError)
                {
                    Debug.Log(www.error);
                }
                else
                {
                    // Show results as text  
                    if (www.responseCode == 200)
                    {
                        Debug.Log(www.downloadHandler.text);
                    }
                }
            }

        }
    }


    public IEnumerator DownLoad(string desFileName,string url)
    {
        string url1 = url ;
        if(File.Exists(desFileName))File.Delete(desFileName);
        if (!File.Exists(desFileName))
        {
            UnityWebRequest request = UnityWebRequest.Get(url1);
            yield return request.Send();
            if (request.isDone)
            {
                int packLength = 1024 * 20;
                byte[] data = request.downloadHandler.data;
                int nReadSize = 0;
                byte[] nbytes = new byte[packLength];
                using (FileStream fs = new FileStream(desFileName, FileMode.Create))
                using (Stream netStream = new MemoryStream(data))
                {
                    nReadSize = netStream.Read(nbytes, 0, packLength);
                    while (nReadSize > 0)
                    {
                        fs.Write(nbytes, 0, nReadSize);
                        nReadSize = netStream.Read(nbytes, 0, packLength);
                        double dDownloadedLength = fs.Length * 1.0 / (1024 );//* 1024
                        double dTotalLength = data.Length * 1.0 / (1024 );//* 1024
                        string ss = string.Format("已下载 {0:F}K / {1:F}K", dDownloadedLength, dTotalLength);
//                      if(OnDownloadProgressEvent!=null)
//                      {
//                          OnDownloadProgressEvent.Invoke(ss);
//                      }
                        Debug.Log(ss);
                        yield return null;
                    }

                }

                byte[] bytes = request.downloadHandler.data;
                Texture2D texture2D = new Texture2D(256,256);
                texture2D.LoadImage(bytes);
                texture2D.Apply();
                _rawImage.texture = texture2D;
            }

        }
//      if (OnDownloadCompleteEvent != null)
//      {
//          Debug.Log("download  finished");
//          OnDownloadCompleteEvent.Invoke();
//      }
    }

客户端的效果: 可以展示服务器下载下来的图片

服务器的效果:可以接收客户端上传上来的图片
这里写图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值