在使用Django多年之后,我正在学习asp.net,所以我可能会错过一些对大家都非常容易的东西。
我需要使用react上传图像,计算图像的一些指标(不必将其保存在服务器中),然后使用JSON对象返回这些指标。
到目前为止,我正在尝试使用此代码,但仅收到错误404。
反应成分:
import React, { Component } from 'react';
import axios from 'axios';
export class DetectObject extends Component {
displayName = DetectObject.name
constructor(props) {
super(props);
this.state = {
selectedFile : null,
items: [],
loading: true,
};
}
fileUploadHandler = () => {
const fd = new FormData();
fd.append('image', this.state.selectedFile, this.state.selectedFile.name);
axios.post('api/Image/Upload', fd)
.then(response => { console.log(response); });
}
fileSelectedHandler = event => {
this.setState({ selectedFile: event.target.files[0] });
}
render() {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: <p>The content was loaded</p>;
return (
<div>
<h1>Object Detection</h1>
<p>Load an image.</p>
<input type="file" onChange={this.fileSelectedHandler} /><br/>
<button onClick={this.fileUploadHandler}>Upload Image</button><br/>
{contents}
</div>
);
}
}
ImageController.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AspObjectDetection.Controllers
{
[Route("api/[controller]")]
public class ImageController : ControllerBase
{
[HttpPost]
public ActionResult Upload(IFormFile file)
{
Console.WriteLine("hello from controller Image");
if (file == null || file.Length == 0)
throw new Exception("File is empty!");
return Content("hello world!"+file.FileName);
}
}
}
它甚至没有打印“来自图像控制器的hello”消息。我的控制器出问题了吗?我的控制器曾经被叫过吗?
答案 0 :(得分:1)
尝试使用FromFormAttribute
已编辑
[HttpPost("[action]")]
public ActionResult Upload([FromForm] IFormFile file)
{
Console.WriteLine("hello from controller Image");
if (file == null || file.Length == 0)
throw new Exception("File is empty!");
return Content("hello world!"+file.FileName);
}