我正在尝试使用Knokout JS和web api上传图像。这是我的代码
self.sendFeedback = function () {
self.result('');
var feedBackData = {
versionId: self.versionId(),
text: self.feedbackText(),
screenShot: self.fileInput
};
$.ajax({
type: 'POST',
url: apiUrl + '/Feedback/Add',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(feedBackData)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
}
我正在使用此自定义绑定
https://github.com/TooManyBees/knockoutjs-file-binding
然后在我的脚本代码中我正在做这个
public void Add(HttpPostedFileBase screenShot, String versionId, String text)
{
String imgId = null;
int count = HttpContext.Current.Request.Files.Count;
if (screenShot != null && screenShot.ContentLength > 0)
{
Images img = Images.Create().Save();
imgId = img.Id;
BlobHelper.PutFile(imgId, screenShot.InputStream);
}
Feedback.Create(versionId, text, imgId).Save();
}
我不确定代码的服务器部分。我到目前为止已写过这个
let composer = TWTRComposer()
composer.setText("just setting up my Fabric")
composer.setImage(UIImage(named: "fabric"))
// Called from a UIViewController
composer.showFromViewController(self) { result in
if (result == TWTRComposerResult.Cancelled) {
print("Tweet composition cancelled")
}
else {
print("Sending tweet!")
}
}
关于如何做到这一点的任何想法?
答案 0 :(得分:6)
fileInput
包含base64编码的文件数据。这是一个字符串,所以HttpPostedFileBase不起作用。
更改表单HTML:
<input class="form-control" type="file"
data-bind="file: {data: fileInput}" />
更改viewmodel代码,如下所示:
// store file data here
self.fileInput = ko.observable(); // is this present already?
var feedBackData = {
versionId: self.versionId(),
text: self.feedbackText(),
screenShot: self.fileInput()
};
$.ajax({
type: 'POST',
url: apiUrl + '/Feedback/Add',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(feedBackData)
}).done(function (data) {
self.result("Done!");
}).fail(showError);
如果控制器方法在API控制器中,它应该接受JSON,模型绑定器将提取值:
public void Add(String screenShot, String versionId, String text)
{
String imgId = null;
if(!String.IsNullOrEmpty(screenShot))
{
Byte[] data = Convert.FromBase64String(screenShot);
// rest of code omitted
很抱歉无法对此语法等进行测试,但应该让您走上正确的轨道。
调试Knockout页面的一个好建议是在开发时使用这一行,这样你就可以看到viewModel中发生了什么:
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
有关更多帮助,请参阅http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html。