0
Try this
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Upload and Drag Images with Knockout.js</title>
</head>
<body>
<div>
<label>Upload or drag images:</label>
<input type="file" multiple="true" accept="image/*" data-bind="event: { change: handleFileSelect, dragover: handleDragOver, drop: handleDrop }">
</div>
<div>
<button data-bind="click: saveImages">Save Images</button>
</div>
<div>
<ul data-bind="foreach: imageData">
<li>
<span data-bind="text: name"></span>
<img data-bind="attr: { src: data }" width="100">
</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js"></script>
<script>
function ViewModel() {
var self = this;
self.imageData = ko.observableArray([]);
self.handleFileSelect = function(evt) {
var files = evt.target.files; // FileList object
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
// Push the image data onto the array.
self.imageData.push({
name: escape(theFile.name),
data: e.target.result
});
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
};
self.handleDragOver = function(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
};
self.handleDrop = function(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
// Push the image data onto the array.
self.imageData.push({
name: escape(theFile.name),
data: e.target.result
});
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
};
self.saveImages = function() {
// Loop through the image data and save each one using Web API.
ko.utils.arrayForEach(self.imageData(), function(image) {
// Use AJAX to POST the image data to the server.
$.ajax({
type: 'POST',
url: 'http://yourserver.com/saveimage',
data: {
name: image.name,
data: image.data
},
success: function() {
// Do something when the image has been saved.
},
error: function() {
// Handle errors here.
}
});
});
};
}
ko.applyBindings(new ViewModel());
</script>
</body>
</html>
