'How to send post request from c# windows forms to a laravel api with files?
I have a windows form that will send a post request to my simple laravel api.
Here's what I have done so far:
private async void UploadScreenshot(string employee_id, string filepath)
{
string url = "http://127.0.0.1:8000/api/upload-screenshot";
using (HttpClient client = new HttpClient())
{
var multiForm = new MultipartFormDataContent();
Image ssimage = Image.FromFile(filepath);
var byteimg = ImageToByteArray(ssimage);
ByteArrayContent screenshotimg = new ByteArrayContent(byteimg);
multiForm.Add(new ByteArrayContent(byteimg), "files");
multiForm.Add(new StringContent(employee_id), "emp_number");
var response = await client.PostAsync(url, multiForm);
var responseString = await response.Content.ReadAsStringAsync();
System.Windows.MessageBox.Show(responseString);
//Console.WriteLine(responseString);
}
}
this code is working only for StringContent.but in my ByteArrayContent it returns null. Event using the MultipartFormDataContent. I tried every answer here in Stackoverflow since yesterday but no luck for me.
this is my Laravel API controller:
public function UploadScreenshot(Request $request){
$emp_number = $request->emp_number; //this is working..
$file = $request->files; //this is null
if ($request->hasFile('screenshot')) {
$file = request()->file('files');
$fname = date('YmdHis');
$ext = $request->files->extension();
$filename = $fname . '.' . $ext;
$file->storeAs('screenshots/', $filename, ['disk' => 'private']);
}
}
Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
