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



我试图在我的net core应用程序中获取和接收数据。此代码有效:


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

But if I try to send object {file and string} i recieve just a string field ImageDTO.FileName. ImageDTO.Image is null.

Here is the code:



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

clientside:


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 method i tried like this and result was the same:

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

console output: FileName: 123 NULL IMAGE: Something wrong! Object reference not set to an instance of an object.

I check this How to upload image from React to ASP.NET Core Web API?

but... if i asking it`s not worked for me. help

You can try to usee.target.files[0]to get the selected file, like below.

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

最新更新