03. Node.js 서버에 연동하여 Image Upload 및 Download하기

Server/Study 2019. 7. 1. 15:57



Node.js 웹서버와 연동하여 Image를 Upload하고 Download하는 것을 만들었다.


Upload는 POST 방식으로, Download는 Unity의 UnityWebRequestTexture.GetTexture()를 이용하여 만들었다.


찾아봐도 정보가 별로없고, 제대로 생각을 못해서 그런지 좀 버벅였다.


그래도 열심히 찾아봐서 도움이 많이된 것 같다.


추후에 다시 연습해봐야겠다.



Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
const express = require('express');
const mysql = require('mysql');
const multer = require('multer');
const fs = require('fs');
const app = express();
var router = express.Router();
module.exports = router;
 
app.use(express.json());
console.log(__dirname + '/uploads');
app.use(express.static(__dirname + '/uploads'));
 
app.listen(3005, () =>
{
    console.log("서버시작, 3005번 포트");
});
 
let storage = multer.diskStorage({
    destination: function(req, file, callback){
        callback(null"uploads/");
    },
    filename: function(req, file, callback){
        callback(null, file.originalname);
    }
});
 
let upload = multer({
    storage: storage
});
 
app.post('/api/uploadimage', upload.single("imgfile"), (req, res, next) =>
{
    let file = req.file;
 
    console.log("접속함");
 
    res.json({
        success: true,
        imageurl: `http://127.0.0.1:3005/uploads/'${req.filename}'`
    });
});
cs

Client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using Newtonsoft.Json;
 
public class packet
{
    public int errorno;
}
 
public class req_uploadimage
{
    public string name;
}
 
public class res_uploadimage : packet
{
    public bool success;
}
 
public class req_getimage
{
    public string url;
}
 
public class res_getimage : packet
{
    public string imagename;
}
 
public class App : MonoBehaviour
{
    public Sprite sampleImage;
    public Button btnUploadImage;
    public Button btnDownloadImage;
    public Image image;
 
    private string serverPath = "http://127.0.0.1:3005";
    private void Start()
    {
        this.SetBtnsEvent();
    }
 
    private void SetBtnsEvent()
    {
        this.btnUploadImage.onClick.AddListener(() =>
        {
            var reqUploadImage = new req_uploadimage();
            this.sampleImage.name = "imgfile";
            reqUploadImage.name = "imgfile";
            var json = JsonConvert.SerializeObject(reqUploadImage);
 
            StartCoroutine(this.Upload(json, (result) =>
            {
                var responseResult = JsonConvert.DeserializeObject<res_uploadimage>(result);
                Debug.Log("성공여부 : " + responseResult.success);
            }));
        });
 
        this.btnDownloadImage.onClick.AddListener(() =>
        {
            StartCoroutine(this.GetImage("sampleimage.png", (result) =>
            {
                var tex2D = (Texture2D)result;
                var rect = new Rect(00, tex2D.width, tex2D.height);
                this.image.sprite = Sprite.Create(tex2D, rect, new Vector2(0.5f, 0.5f));
 
            }));
        });
    }
 
    private IEnumerator GetImage(string imagename, System.Action<Texture> OnCompleteDownload)
    {
        var path = string.Format("{0}/{1}"this.serverPath, imagename);
        UnityWebRequest webRequest = UnityWebRequestTexture.GetTexture(path);
        yield return webRequest.SendWebRequest();
 
        if (webRequest.isNetworkError || webRequest.isHttpError)
        {
            Debug.Log(webRequest.error);
        }
        else
        {
            OnCompleteDownload(((DownloadHandlerTexture)webRequest.downloadHandler).texture);
        }
    }
 
    private IEnumerator Upload(string data, System.Action<string> OnCompleteUpload)
    {
        //이미지 sprite -> texture2d로 변환후 png로 변환
        var img = this.sampleImage;
        var newTex = new Texture2D((int)img.rect.width, (int)img.rect.height);
        var newColors = img.texture.GetPixels((int)img.textureRect.x, (int)img.textureRect.y, (int)img.textureRect.width, (int)img.textureRect.height);
        newTex.SetPixels(newColors);
        newTex.Apply();
        var tex = ImageConversion.EncodeToPNG(newTex);
 
        var byteArr = Encoding.UTF8.GetBytes(data);
        List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
        formData.Add(new MultipartFormFileSection("imgfile", tex, "sampleimage.png""image/png"));
 
        var path = string.Format("{0}/{1}"this.serverPath, "api/uploadimage");
        UnityWebRequest webRequest = UnityWebRequest.Post(path, formData);
        webRequest.downloadHandler = new DownloadHandlerBuffer();
        yield return webRequest.SendWebRequest();
 
        var result = webRequest.downloadHandler.text;
        OnCompleteUpload(result);
    }
}
 
cs


'Server > Study' 카테고리의 다른 글

02. 로그인 연동 / api 설계  (0) 2019.07.01
01. 로그인/회원가입  (0) 2019.06.28
01. 참고사이트  (0) 2019.06.28
: