首页 > 解决方案 > 如何使用文件获取表单并在网络核心上接收它?

问题描述

我尝试在我的网络核心应用程序中获取和接收数据。此代码有效:



    [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));

但是,如果我尝试发送对象 {file 和 string},我只会收到一个字符串字段 ImageDTO.FileName。ImageDTO.Image 为空。

这是代码:


 

       [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}");
          }
        }

客户端:



    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
          
        
      
    );

onSubmit 方法我试过这样,结果是一样的:

代码>
    
    (有或没有标题)
    
     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);
      }

控制台输出:文件名:123 NULL IMAGE:有问题!你调用的对象是空的。

我检查了这个如何将图像从 React 上传到 ASP.NET Core Web API?

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

标签: javascriptc#reactjsasp.net-core

解决方案


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

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

推荐阅读