使用aurelia上传图像到asp.net核心后端

问题描述 投票:2回答:1

我一直在寻找解决方案,但没有一个指南更新或适合我的意图。我需要将用户上传的图像加载到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();
}

错误信息

enter image description here

javascript c# asp.net-core-mvc aurelia aurelia-fetch-client
1个回答
2
投票

HTML元素<input type="file" />没有属性file,正确的属性是files,所以听起来问题是aurelia / javascript和绑定。

由于files属性是FileList(集合),因此您需要访问集合中的第一个文件。即使你没有使用multiple我认为files仍然是一个集合。

你可以试试这个:

// html 
<input class="hiddenButton" id="images" type="file" accept=".jpeg" files.bind="image">
//                                                                     ^ files

// jss/aurelia
saveImage(image) {
    var form = new FormData();
    form.append('image', image[0]);    // access the first image in collection image[0]

    // the other code remains the same
    //...
}

PS我没有使用aurelia所以不能100%确定这是问题,但希望指出你正确的方向。

PPS:因为files是一个集合,技术上你的视图模型中的image也是一个集合,所以你可以考虑将它重命名为images以使它更清晰(即使你只使用一个图像)。它应该仍然使用image[0],但images[0]会更清楚。

© www.soinside.com 2019 - 2024. All rights reserved.