-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathForm1.cs
116 lines (107 loc) · 3.9 KB
/
Form1.cs
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
116
using System;
using System.IO;
using System.Net;
using System.Windows.Forms;
namespace aQuang
{
public partial class Form1 : Form
{
private int _retryCount = 0;
public Form1()
{
InitializeComponent();
}
private void chooseFileBtn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
fileNametxt.Text = dlg.FileName;
uploadStatustxt.Text = "Status: ready to upload";
}
}
private void uploadBtn_Click(object sender, EventArgs e)
{
if(fileNametxt.Text != "")
{
Upload(fileNametxt.Text, apiUrlTxt.Text, 5, 3000);
}
else
{
MessageBox.Show("Please select file to upload");
}
}
// Upload không bảo mật
// https://stackoverflow.com/a/40219504
private void Upload(
string fileName,
string serverUrl,
int retryLimit = 5,
int retryInterval = 3000)
{
using (var client = new WebClient())
{
try
{
// Init data
uploadStatustxt.Text = "Status: Loading file data...";
var uri = new Uri(serverUrl);
var data = File.ReadAllBytes(fileName);
uploadStatustxt.Text = "Status: Uploading...";
// Init event handlers - Phải để trước khi bắt đầu upload hmmm...
// https://stackoverflow.com/a/982332
client.UploadProgressChanged += (object sender, UploadProgressChangedEventArgs e) =>
{
progressBar.Value = e.ProgressPercentage;
};
client.UploadDataCompleted += (s, e) =>
{
if (e.Error != null)
{
_retryCount++;
if (_retryCount < retryLimit)
{
MessageBox.Show(e.Error.Message + $"\nRetry {_retryCount} after {retryInterval/1000}s...");
SetTimeout(() =>
{
client.UploadDataAsync(uri, data);
}, retryInterval);
}
else
{
_retryCount = 0;
uploadStatustxt.Text = "Status: Upload Failed";
MessageBox.Show(e.Error.Message + "\nReached retry limit. Will stop retry!");
}
}
else
{
_retryCount = 0;
uploadStatustxt.Text = "Status: Upload Success";
MessageBox.Show("Upload Data Completed");
}
};
// Begin upload
client.Headers.Add("fileName", Path.GetFileName(fileName));
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
// https://stackoverflow.com/a/57694261
public void SetTimeout(Action action, int timeout)
{
var timer = new System.Windows.Forms.Timer();
timer.Interval = timeout;
timer.Tick += delegate (object sender, EventArgs args)
{
action();
timer.Stop();
};
timer.Start();
}
}
}