This repository was archived by the owner on May 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathinputfile.js
More file actions
206 lines (176 loc) · 8.84 KB
/
inputfile.js
File metadata and controls
206 lines (176 loc) · 8.84 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
(function () {
window.BlazorInputFile = {
init: function init(elem, componentInstance) {
elem._blazorInputFileNextFileId = 0;
elem.addEventListener('change', function handleInputFileChange(event) {
// Only process if files selected.
if (elem.files.length > 0) {
// Reduce to purely serializable data, plus build an index by ID
elem._blazorFilesById = {};
var fileList = Array.prototype.map.call(elem.files, function (file) {
var result = {
id: ++elem._blazorInputFileNextFileId,
lastModified: new Date(file.lastModifiedDate).toISOString(),
name: file.name,
size: file.size,
type: file.type,
relativePath: file.webkitRelativePath
};
elem._blazorFilesById[result.id] = result;
// Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON
Object.defineProperty(result, 'blob', { value: file });
return result;
});
componentInstance.invokeMethodAsync('NotifyChange', fileList).then(function () {
//reset file value ,otherwise, the same filename will not be trigger change event again
elem.value = '';
}, function (err) {
//reset file value ,otherwise, the same filename will not be trigger change event again
elem.value = '';
throw new Error(err);
});
}
});
},
toImageFile: function toImageFile(elem, fileId, format, maxWidth, maxHeight) {
var originalFile = getFileById(elem, fileId);
return new Promise(function (resolve) {
var originalFileImage = new Image();
originalFileImage.onload = function () { resolve(originalFileImage); };
originalFileImage.src = URL.createObjectURL(originalFile.blob);
}).then(function (loadedImage) {
return new Promise(function (resolve) {
var desiredWidthRatio = Math.min(1, maxWidth / loadedImage.width);
var desiredHeightRatio = Math.min(1, maxHeight / loadedImage.height);
var chosenSizeRatio = Math.min(desiredWidthRatio, desiredHeightRatio);
var canvas = document.createElement('canvas');
canvas.width = Math.round(loadedImage.width * chosenSizeRatio);
canvas.height = Math.round(loadedImage.height * chosenSizeRatio);
canvas.getContext('2d').drawImage(loadedImage, 0, 0, canvas.width, canvas.height);
canvas.toBlob(resolve, format);
});
}).then(function (resizedImageBlob) {
var result = {
id: ++elem._blazorInputFileNextFileId,
lastModified: originalFile.lastModified,
name: originalFile.name, // Note: we're not changing the file extension
size: resizedImageBlob.size,
type: format,
relativePath: originalFile.relativePath
};
elem._blazorFilesById[result.id] = result;
// Attach the blob data itself as a non-enumerable property so it doesn't appear in the JSON
Object.defineProperty(result, 'blob', { value: resizedImageBlob });
return result;
});
},
readFileData: function readFileData(elem, fileId, startOffset, count) {
var readPromise = getArrayBufferFromFileAsync(elem, fileId);
return readPromise.then(function (arrayBuffer) {
var uint8Array = new Uint8Array(arrayBuffer, startOffset, count);
var base64 = uint8ToBase64(uint8Array);
return base64;
});
},
ensureArrayBufferReadyForSharedMemoryInterop: function ensureArrayBufferReadyForSharedMemoryInterop(elem, fileId) {
return getArrayBufferFromFileAsync(elem, fileId).then(function (arrayBuffer) {
getFileById(elem, fileId).arrayBuffer = arrayBuffer;
});
},
readFileDataSharedMemory: function readFileDataSharedMemory(readRequest) {
// This uses various unsupported internal APIs. Beware that if you also use them,
// your code could become broken by any update.
var inputFileElementReferenceId = Blazor.platform.readStringField(readRequest, 0);
var inputFileElement = document.querySelector('[_bl_' + inputFileElementReferenceId + ']');
var fileId = Blazor.platform.readInt32Field(readRequest, 4);
var sourceOffset = Blazor.platform.readUint64Field(readRequest, 8);
var destination = Blazor.platform.readInt32Field(readRequest, 16);
var destinationOffset = Blazor.platform.readInt32Field(readRequest, 20);
var maxBytes = Blazor.platform.readInt32Field(readRequest, 24);
var sourceArrayBuffer = getFileById(inputFileElement, fileId).arrayBuffer;
var bytesToRead = Math.min(maxBytes, sourceArrayBuffer.byteLength - sourceOffset);
var sourceUint8Array = new Uint8Array(sourceArrayBuffer, sourceOffset, bytesToRead);
var destinationUint8Array = Blazor.platform.toUint8Array(destination);
destinationUint8Array.set(sourceUint8Array, destinationOffset);
return bytesToRead;
}
};
function getFileById(elem, fileId) {
var file = elem._blazorFilesById[fileId];
if (!file) {
throw new Error('There is no file with ID ' + fileId + '. The file list may have changed');
}
return file;
}
function getArrayBufferFromFileAsync(elem, fileId) {
var file = getFileById(elem, fileId);
// On the first read, convert the FileReader into a Promise<ArrayBuffer>
if (!file.readPromise) {
file.readPromise = new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function () { resolve(reader.result); };
reader.onerror = function (err) { reject(err); };
reader.readAsArrayBuffer(file.blob);
});
}
return file.readPromise;
}
var uint8ToBase64 = (function () {
// Code from https://github.com/beatgammit/base64-js/
// License: MIT
var lookup = [];
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
}
function tripletToBase64(num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF);
output.push(tripletToBase64(tmp));
}
return output.join('');
}
return function fromByteArray(uint8) {
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(
uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
);
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
);
}
return parts.join('');
};
})();
})();