嘿 m 使用带有敲除的 mvc3 并尝试使用敲除绑定来上传上传的图像并将其保存在数据库中。我能够浏览并获取图像,但无法获取如何保存该图像。我的 html 视图是:
<div data-bind="foreach: { data: images, beforeRemove: beforeRemoveSlot }">
<div>
<input type="file" accept="image/*" data-bind="file: imageFile, fileObjectURL: imageObjectURL, fileBinaryData: imageBinary"/>
<div data-bind="if: imageObjectURL">
<img class="thumb" data-bind="attr: { src: imageObjectURL }"/>
</div>
<div>Size: <span data-bind="text: fileSize"></span> bytes</div>
</div>
</div>
<input type="submit" value="Upload Picture" data-bind="click: upload" />
我的视图模型是:
var windowURL = window.URL || window.webkitURL;
ko.bindingHandlers.file = {
init: function (element, valueAccessor) {
$(element).change(function () {
var file = this.files[0];
if (ko.isObservable(valueAccessor())) {
valueAccessor()(file);
}
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var file = ko.utils.unwrapObservable(valueAccessor());
var bindings = allBindingsAccessor();
if (bindings.fileObjectURL && ko.isObservable(bindings.fileObjectURL)) {
var oldUrl = bindings.fileObjectURL();
if (oldUrl) {
windowURL.revokeObjectURL(oldUrl);
}
bindings.fileObjectURL(file && windowURL.createObjectURL(file));
}
if (bindings.fileBinaryData && ko.isObservable(bindings.fileBinaryData)) {
if (!file) {
bindings.fileBinaryData(null);
} else {
var reader = new FileReader();
reader.onload = function (e) {
bindings.fileBinaryData(e.target.result);
};
reader.readAsArrayBuffer(file);
}
}
}
};
var imageUploadModel = function () {
var self = {};
var slotModel = function () {
var that = {};
that.imageFile = ko.observable();
that.imageObjectURL = ko.observable();
that.imageBinary = ko.observable();
that.fileSize = ko.computed(function () {
var file = this.imageFile();
return file ? file.size : 0;
}, that);
that.firstBytes = ko.computed(function () {
if (that.imageBinary()) {
var buf = new Uint8Array(that.imageBinary());
var bytes = [];
for (var i = 0; i < Math.min(10, buf.length); ++i) {
bytes.push(buf[i]);
}
return '[' + bytes.join(', ') + ']';
} else {
return '';
}
}, that);
return that;
};
self.beforeRemoveSlot = function (element, index, data) {
if (data.imageObjectURL()) {
windowURL.revokeObjectURL(data.imageObjectURL());
}
$(element).remove();
};
self.images = ko.observableArray([slotModel()]);
self.addSlot = function () {
self.images.push(slotModel());
};
self.removeSlot = function (data) {
self.images.remove(data);
};
return self;
} ();
imageUploadModel.upload = function () {
}
$(document).ready(function () {
ko.applyBindings(imageUploadModel);
});
任何人都可以建议我如何在上传按钮单击时保存图像??????