【问题标题】:Uploading images using aurelia to asp.net core backend使用 aurelia 将图像上传到 asp.net 核心后端
【发布时间】: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


【解决方案1】:

HTML元素&lt;input type="file" /&gt;没有属性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] 会更清晰。

【讨论】:

  • 改变了工作!谢谢!原来是这样,但我已经更改了它,看看它是否是另一个问题的原因,忘记了撤消更改。
  • @JurgenAquilina 我很高兴它成功了。如果有帮助,请也投票:)
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
相关资源
最近更新 更多