As The last ship sailed towards the distant horizon I sat there watching on a rock My mind slowly drifting away Forming into my... Dreamtale
Upload Files in One Request
2019-01-26 / 4 min read

Client Codes

  • Core Codes

    public class UploadFile
    {
        public UploadFile()
        {
            ContentType = "application/octet-stream";
        }
    
        public string Name { get; set; }
    
    public string Filename { get; set; }
    public string ContentType { get; set; }
    public string FilePath { get; set; }
}

public static bool HttpUploadFile(string url, List<UploadFile> files,
    Dictionary<string, string> nvc)
{
    Debug.Log(string.Format("Uploading {0} to {1}", files[0], url));
    var request = WebRequest.Create(url);
    request.Method = "POST";
    var boundary = "---------------------------" +
                   DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);
    request.ContentType = "multipart/form-data; boundary=" + boundary;
    boundary = "--" + boundary;

    using (var requestStream = request.GetRequestStream())
    {
        // Write the values
        foreach (string name in nvc.Keys)
        {
            var buffer = Encoding.ASCII.GetBytes(boundary + "\r\n");
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.ASCII.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"{1}{1}",
                name, "\r\n"));
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.UTF8.GetBytes(nvc[name] + "\r\n");
            requestStream.Write(buffer, 0, buffer.Length);
        }

        // Write the files
        foreach (var file in files)
        {
            var buffer = Encoding.ASCII.GetBytes(boundary + "\r\n");
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.UTF8.GetBytes(string.Format(
                "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", file.Name, file.Filename,
                "\r\n"));
            requestStream.Write(buffer, 0, buffer.Length);
            buffer = Encoding.ASCII.GetBytes(string.Format("Content-Type: {0}{1}{1}", file.ContentType,
                "\r\n"));
            requestStream.Write(buffer, 0, buffer.Length);
            FileStream fileStream = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read);
            byte[] buffer1 = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer1, 0, buffer1.Length)) != 0)
            {
                requestStream.Write(buffer1, 0, bytesRead);
            }

            fileStream.Close();
            buffer = Encoding.ASCII.GetBytes("\r\n");
            requestStream.Write(buffer, 0, buffer.Length);
        }

        var boundaryBuffer = Encoding.ASCII.GetBytes(boundary + "--");
        requestStream.Write(boundaryBuffer, 0, boundaryBuffer.Length);
    }

    WebResponse wresp = null;
    try
    {
        wresp = request.GetResponse();
        Stream stream2 = wresp.GetResponseStream();
        StreamReader reader2 = new StreamReader(stream2);
        Debug.Log(string.Format("File uploaded, server response is: {0}", reader2.ReadToEnd()));

        return true;
    }
    catch (Exception ex)
    {
        Debug.LogError("Error uploading file: " + ex.Message);
        if (wresp != null)
        {
            wresp.Close();
            wresp = null;
        }

        return false;
    }
    finally
    {
        request = null;
    }
}
```
  • How to use

    HttpUploadFile("http://localhost:8080/upload", new List<UploadFile>
    {
        new UploadFile
        {
            Name = "file1",
            Filename = rootNS.ToLower() + ".txt",
            ContentType = "text/plain",
            FilePath = resPath + "/" + rootNS.ToLower() + ".txt"
        },
        new UploadFile
        {
            Name = "file2",
            Filename = rootNS.ToLower() + "lua.zip.txt",
            ContentType = "text/plain",
            FilePath = resPath + "/" + rootNS.ToLower() + "lua.zip.txt"
        },
        new UploadFile
        {
            Name = "file3",
            Filename = rootNS.ToLower() + ".zip",
            ContentType = "application/zip",
            FilePath = resPath + "/" + rootNS.ToLower() + ".zip.txt"
        },
    
    }, 
    new Dictionary<string, string>()
    {
        {"para1", para1.ToLower()},
        {"para2", para2.GetValue()},
    });
    
    

Server Code in Nodejs

  • install express-fileupload

    # With NPM 
    npm install --save express-fileupload
    
    # With Yarn 
    yarn add express-fileupload
    
  • receive files with express-fileupload

    app.post('/upload', function (req, res) {
        handled = false;
        // console.log(req)
        if (Object.keys(req.files).length == 0) {
            return res.status(400).send('No files were uploaded.');
        }
    
        // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
        let file1 = req.files.file1;
        let file2 = req.files.file2;
        let file3 = req.files.file3;
        let file4 = req.files.file4; 
    
        var para1 = req.body.para1;
        var para2 = req.body.para2;
    
        if (file1) {
    
        }
    
        if (file2) {
    
        }
    
        if (file3) {
    
        }
    
        if (file4) {
    
        }
    }