【发布时间】:2019-07-20 11:34:16
【问题描述】:
我一直在为此寻找解决方案,但没有任何指南更新或适合我的意图。我需要将用户上传的图像加载到 javascript/aurelia 中,然后使用其 http fetch 客户端将其发送到 asp.net 核心后端,以便将图像保存在磁盘上(而不是数据库中)。我目前正在使用以下代码,但出现以下错误并且没有保存图像。
从用于上传图片的html代码中提取
<input class="hiddenButton" id="images" type="file" accept=".jpeg" file.bind="image">
<button class="upload" onclick="document.getElementById('images').click()">
<i class="fa fa-pencil" style="color:green"></i>
</button>
用于调用保存的 javascript 代码的提取
save() {
this.api.saveEmployee(this.employee).then(employee => this.employee = employee);
this.ea.publish(new EmployeeAdded(this.employee));
this.api.saveImage(this.image);
return this.employee;
}
Javascript/aurelia 代码
saveImage(image) {
var form = new FormData()
form.append('image', image)
this.http.fetch('/api/Images', {
method: 'POST',
//headers: { 'Content-Type': image.type },
body: form
})
.then(response => {
return response
})
.catch(error => {
console.log("Some Failure...");
throw error.content;
})
return true;
}
Asp.net 核心 MVC 代码(后端)
[HttpPost]
public async Task<IActionResult> SaveImage(IFormFile file)
{
Console.WriteLine("Images controller");
var filePath = Path.Combine(Directory.GetCurrentDirectory(),"Image");
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Ok();
}
错误信息
【问题讨论】:
-
这是一个服务器错误,将服务器代码包装在
try{} catch{}中等等一些调试。然后在这里发布错误 -
按照建议,我添加了 try{} catch{},它消除了错误,而没有在控制台上引入任何新错误。现在甚至可以根据需要创建图像文件,但似乎正在保存的文件已损坏,因为当我将其保存为 png 或 jpg 并尝试在 Windows 10 上打开它时,它显示“我们似乎不支持这种文件格式. 你知道可能是什么原因,因为我的调试没有给我这个指示吗?
-
添加到我之前的评论:没有字节被写入创建的文件
-
file是否为空?file.Length是什么? -
您能否显示您的图片的 HTML 以及对
saveImage的调用?
标签: javascript c# asp.net-core-mvc aurelia aurelia-fetch-client