Javascript 如何用文件获取表单并在网络核心上接收?

Javascript 如何用文件获取表单并在网络核心上接收?,javascript,c#,reactjs,asp.net-core,Javascript,C#,Reactjs,Asp.net Core,我尝试在我的NetCore应用程序中获取和接收数据。 此代码适用于: [HttpPost] public JsonResult Post([FromBody] User user) { var s = HttpContext.Request.QueryString; Console.WriteLine($"name: {user.Name}, age: {user.Age}"); return Json(user); }

我尝试在我的NetCore应用程序中获取和接收数据。 此代码适用于:



    [HttpPost]
    public JsonResult Post([FromBody] User user)
    {
      var s = HttpContext.Request.QueryString;
      Console.WriteLine($"name: {user.Name}, age: {user.Age}");
      return Json(user);
    }
    
    public class User
      {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
      }
    
    const url = "http://localhost:5000/Home/Post";
    const user = {Name: 'valenok', Age: 25 };
    fetch(url, {
        method: 'POST', // or 'PUT'
        body: JSON.stringify(user), 
        headers: {
            'Accept': 'application/json; charset=utf-8',
            'Content-Type': 'application/json;charset=UTF-8'
        }
    }).then(res => res.json())
        .then(response => console.log('Success:', JSON.stringify(response)))
            .catch(error => console.error('Error:', error));

[HttpPost]
公共JsonResult帖子([FromBody]用户)
{
var s=HttpContext.Request.QueryString;
WriteLine($“name:{user.name},age:{user.age}”);
返回Json(用户);
}
公共类用户
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共整数{get;set;}
}
常量url=”http://localhost:5000/Home/Post";
const user={Name:'valenok',年龄:25};
获取(url{
方法:“POST'、//或“PUT”
正文:JSON.stringify(用户),
标题:{
“Accept”:“application/json;charset=utf-8”,
“内容类型”:“应用程序/json;字符集=UTF-8”
}
}).then(res=>res.json())
.then(response=>console.log('Success:',JSON.stringify(response)))
.catch(error=>console.error('error:',error));
但如果我尝试发送对象{file and string},我只会收到一个字符串字段ImageDTO.FileName。ImageDTO。图像为空

代码如下:


 

       [HttpPost]
        public async Task AddFile(ImageDTO img)
        {
          Console.WriteLine($"FileName: {img.Image}");
          Console.WriteLine($"FileName: {img.FileName}");
          if (img.Image == null)
          {
            Console.WriteLine("NULL");
          }
          try
          {
            string path = "/Files/" + img.FileName;
            using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
            {
              Console.WriteLine($"IMAGE: {img.Image}");
              await img.Image.CopyToAsync(fileStream);
            }
            return Json($"File saved to{path}");
          }
          catch (System.Exception ex)
          {
            Console.WriteLine($"Something wrong! {ex.Message}");
            return Json($"Something wrong! {ex.Message}");
          }
        }

[HttpPost]
公共异步任务添加文件(ImageDTO img)
{
WriteLine($“文件名:{img.Image}”);
WriteLine($“文件名:{img.FileName}”);
如果(img.Image==null)
{
控制台。写入线(“空”);
}
尝试
{
字符串路径=“/Files/”+img.FileName;
使用(var fileStream=newfilestream(appEnvironment.WebRootPath+path,FileMode.Create))
{
WriteLine($“IMAGE:{img.IMAGE}”);
等待img.Image.CopyToAsync(文件流);
}
返回Json($“保存到{path}的文件”);
}
catch(System.Exception-ex)
{
WriteLine($“出错了!{ex.Message}”);
返回Json($“有问题!{ex.Message}”);
}
}
客户端:



    class FileDownloadForm1 extends React.Component {
      state = {
        file: null,
        title: null,
      };
    
      onFileChange = (e) => {
        this.setState({file: e.target.value})
        console.log(this.state.file);
      };
    
      onTitleChange = (e) => {
        
        this.setState({title: e.target.value})
        console.log(this.state.title);
      };
    
      onSubmit = async (e) => {
        e.preventDefault();
        const formData  = new FormData();
        const url = "http://localhost:5000/Home/AddFile";
        formData.append("FileName", this.state.title);
        formData.append("Image", this.state.file);
        console.log(this.state.file);
        console.log(this.state.title);
        let xhr = new XMLHttpRequest();
        xhr.open('POST', url);
        xhr.send(formData);
      }
    
     render() {
    return (
      
        
          
            Choose file to upload
            
          
          
            Simplae label
            
            {/* {this.onTitleChange(e)}} name="title">*/}
          
          
            Submit
          
        
      
    );

类FileDownloadForm1扩展了React.Component{
状态={
文件:null,
标题:空,
};
onFileChange=(e)=>{
this.setState({file:e.target.value})
log(this.state.file);
};
onTitleChange=(e)=>{
this.setState({title:e.target.value})
console.log(this.state.title);
};
onSubmit=async(e)=>{
e、 预防默认值();
const formData=new formData();
常量url=”http://localhost:5000/Home/AddFile";
append(“FileName”,this.state.title);
append(“Image”,this.state.file);
log(this.state.file);
console.log(this.state.title);
设xhr=newXMLHttpRequest();
xhr.open('POST',url);
xhr.send(formData);
}
render(){
返回(
选择要上载的文件
单纯形标签
{/*{this.onTitleChange(e)}name=“title”>*/}
提交
);
在Submit方法中,我像这样尝试,结果是一样的:

code> (with headers or not)

     onSubmit = async (e) => {
        e.preventDefault();
        const formData  = new FormData();
        const url = "http://localhost:5000/Home/AddFile";
        formData.append("FileName", this.state.title);
        formData.append("Image", this.state.file);
        const result = await fetch(url, {
          method: 'POST',
          body: formData
        });
        const response = await result.json();
        console.log(response);
      }
代码>
(是否带有标题)

onSubmit=async(e)=>{
e、 预防默认值();
const formData=new formData();
常量url=”http://localhost:5000/Home/AddFile";
append(“FileName”,this.state.title);
append(“Image”,this.state.file);
const result=等待获取(url{
方法:“POST”,
正文:formData
});
const response=wait result.json();
控制台日志(响应);
}
控制台输出: 文件名:123 无效的 图片: 出现问题!对象引用未设置为对象的实例

我查一下


但是…如果我问它对我不起作用。帮助

好吧…我做了这个,它起作用了。文件被保存了。我的js代码中有错误。有人知道比这更简单的方法吗。从表单获取文件的反应方式。不是:



    const fileField = document.querySelector('input[type="file"]');
    formData.append("Image", fileField.files[0]);

const fileField=document.querySelector('input[type=“file”]”);
formData.append(“Image”,fileField.files[0]);
完整代码:



    onSubmit = async (e) => {
        e.preventDefault();
        const formData  = new FormData();
        const fileField = document.querySelector('input[type="file"]');
        const url = "http://localhost:5000/Home/AddFile";
        formData.append("FileName", this.state.title);
        formData.append("Image", fileField.files[0]);
        const result = await fetch(url, {
          method: 'POST',
          body: formData
        });
        const response = await result.json();
        console.log(response);
      }
    
      render() {
        return (
          
            
              
                Choose file to upload
                
              
              
                Simplae label
                
                {/* {this.onTitleChange(e)}} name="title">*/}
              
              
                Submit
              
            
          
        );
      }
    };

onSubmit=async(e)=>{
e、 预防默认值();
const formData=new formData();
const fileField=document.querySelector('input[type=“file”]”);
常量url=”http://localhost:5000/Home/AddFile";
append(“FileName”,this.state.title);
formData.append(“Image”,fileField.files[0]);
const result=等待获取(url{
方法:“POST”,
正文:formData
});
const response=wait result.json();
控制台日志(响应);
}
render(){
返回(
选择要上载的文件
单纯形标签
{/*{this.onTitleChange(e)}name=“title”>*/}
提交
);
}
};

您可以尝试使用
e.target.files[0]
获取所选文件,如下所示

  onFileChange = (e) => {
    this.setState({ file: e.target.files[0] });
    console.log(this.state.file);
  };

我不知道为什么不将jsx syntaxpublic类ImageDTO{public string FileName{get;set;}public IFormFile Image{get;set;}}显示到{get;set;}}}并且我尝试了太公开的异步任务AddFile([FromForm]ImageDTO img){请检查您在浏览器开发人员工具网络选项卡中发布的实际请求和数据。StackOverFlow为什么不在react类中显示我的渲染方法?谢谢!是的!我是js的新手。很简单,我15分钟前就知道了。但我非常感谢您的帮助