问题描述
我正在尝试发送包含数据和图像文件的发布请求。但是当我在下面发送我的代码时,出现错误。请在客户端查看下面的代码。
varCombo = {}
counter = 0
for i in infos:
frame = Frame(principalFrame,bd=1)
frame.grid(row=counter,column=0,pady=20)
frame.columnconfigure(0,weight=1)
label = Label(frame,text=i.name)
label.grid(row=0,sticky="news")
label.columnconfigure(0,weight=1)
var1 = StringVar(window)
var1.set(i.default)
combo = ttk.Combobox(frame,state="readonly",textvariable=var1,values=i.values)
combo.grid(row=1,sticky="news")
combo.columnconfigure(0,weight=1)
combo.rowconfigure(0,weight=1)
varCombo[i.name] = var1
counter = counter + 1
在WebAPI上,控制器显示在下面
public async Task<HttpContent> PostRequestAsync(string requestUri)
{
string jsonString = string.Empty;
StringContent stringJsonContent = default(StringContent);
HttpResponseMessage requestResponse = new HttpResponseMessage();
try
{
stringJsonContent = new StringContent(jsonString,Encoding.UTF8,"application/json");
requestResponse = await this.httpClient.PostAsync(requestUri,stringJsonContent);
if (requestResponse.IsSuccessStatusCode)
{
return requestResponse?.Content;
}
else if (requestResponse.StatusCode == HttpStatusCode.InternalServerError)
{
}
else if (requestResponse.StatusCode == HttpStatusCode.Unauthorized)
{
}
}
catch (Exception ex)
{
throw ex.InnerException;
}
return requestResponse?.Content;
}
}
模型是
[HttpPost]
public async Task<ActionResult> UpdateProfile([FromForm] UpdateProfile updateProfile)
但是在POSTMAN中,我使用下面的命令成功上传了文件,因此我感觉客户端的代码有问题。任何人都可以建议我需要在代码上添加什么才能工作?我遇到错误,无法发送请求。
解决方法
在客户代码中,您不使用表单对象来传输数据。 StringContent存储表单的值而不是键。您可以使用MultipartFormDataContent对象来传输所有表单和文件。另外,我给出一个示例代码。
客户端中的代码。
class Program
{
static async Task Main(string[] args)
{
await PostRequestAsync(@"D:\upload\1.jpg",new HttpClient(),"https://localhost:44370/api/UpdateProfile");
}
public static async Task<string> PostRequestAsync(string filePath,HttpClient _httpClient,string _url)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"File [{filePath}] not found.");
}
//Create form
using var form = new MultipartFormDataContent();
var bytefile = AuthGetFileData(filePath);
var fileContent = new ByteArrayContent(bytefile);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
form.Add(fileContent,"Image",Path.GetFileName(filePath));
//the other data in form
form.Add(new StringContent("Mr."),"firstName");
form.Add(new StringContent("Loton"),"lastName");
form.Add(new StringContent("Names--"),"Name");
var response = await _httpClient.PostAsync($"{_url}",form);
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
return responseContent;
}
//Convert file to byte array
public static byte[] AuthGetFileData(string fileUrl)
{
using (FileStream fs = new FileStream(fileUrl,FileMode.OpenOrCreate,FileAccess.ReadWrite))
{
byte[] buffur = new byte[fs.Length];
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(buffur);
bw.Close();
}
return buffur;
}
}
}
WebApi中的操作
[ApiController]
[Route("[controller]")]
public class ApiController:Controller
{
[HttpPost("get")]
public string get([FromForm]UpdateProfile updateProfile)
{
return "get";
}
[HttpPost("UpdateProfile")]
public async Task<ActionResult> UpdateProfile([FromForm] UpdateProfile updateProfile)
{
return Json("The result data ");
}
}
模型
public class UpdateProfile : BaseModel
{
public string firstName { get; set; }
public string lastName { get; set; }
public IFormFile Image { get; set; }
}
public class BaseModel
{
public string Name { get; set; }
}