forked from davidcann/deepDropUpload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DCFileUpload.j
107 lines (85 loc) · 2.43 KB
/
DCFileUpload.j
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
@import <AppKit/CPPanel.j>
/*
DCFileUploadDelegate protocol
- (void)fileUploadDidBegin:(DCFileUpload)theController;
- (void)fileUploadProgressDidChange:(DCFileUpload)theController;
- (void)fileUploadDidEnd:(DCFileUpload)theController;
*/
@implementation DCFileUpload : CPObject {
CPString name @accessors;
float progress @accessors;
id delegate @accessors;
CPURL uploadURL @accessors;
id file;
var xhr;
BOOL isUploading;
}
- (id)initWithFile:(id)theFile {
self = [super init];
file = theFile;
progress = 0.0;
isUploading = NO;
return self;
}
- (void)begin {
[self processXHR];
}
- (void)processXHR {
xhr = new XMLHttpRequest();
var fileUpload = xhr.upload;
fileUpload.addEventListener("progress", function(event) {
if (event.lengthComputable) {
[self setProgress:event.loaded / event.total];
[self fileUploadProgressDidChange];
}
}, false);
fileUpload.addEventListener("load", function(event) {
[self fileUploadDidEnd];
}, false);
fileUpload.addEventListener("error", function(evt) {
CPLog("error: " + evt.code);
}, false);
xhr.addEventListener("load", function(evt) {
if (xhr.responseText)
[self fileUploadDidReceiveResponse:xhr.responseText];
}, NO);
xhr.open("POST", [uploadURL absoluteURL]);
xhr.setRequestHeader("If-Modified-Since", "Mon, 26 Jul 1997 05:00:00 GMT");
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.send(file);
[self fileUploadDidBegin];
};
- (void)fileUploadDidBegin {
isUploading = YES;
if ([delegate respondsToSelector:@selector(fileUploadDidBegin:)]) {
[delegate fileUploadDidBegin:self];
}
}
- (void)fileUploadProgressDidChange {
isUploading = YES;
if ([delegate respondsToSelector:@selector(fileUploadProgressDidChange:)]) {
[delegate fileUploadProgressDidChange:self];
}
}
- (void)fileUploadDidEnd{
isUploading = NO;
if ([delegate respondsToSelector:@selector(fileUploadDidEnd:)])
[delegate fileUploadDidEnd:self];
}
- (void)fileUploadDidReceiveResponse:(CPString)aResponse
{
if ([delegate respondsToSelector:@selector(fileUpload:didReceiveResponse:)])
[delegate fileUpload:self didReceiveResponse:aResponse];
}
- (BOOL)isUploading {
return isUploading;
}
- (void)cancel {
isUploading = NO;
xhr.abort();
}
@end