繁体   English   中英

How to send post request from c# windows forms to a laravel api with files?

[英]How to send post request from c# windows forms to a laravel api with files?

我有一个 windows 表单,它将向我的简单 laravel api 发送一个发布请求。

这是我到目前为止所做的:

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

        }
    }

此代码仅适用于StringContent 。但在我的ByteArrayContent中,它返回 null。 使用MultipartFormDataContent的事件。 从昨天开始,我在 Stackoverflow 中尝试了所有答案,但对我来说没有运气。

这是我的 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']);

    }
}

谢谢。

这就是我所做的并且像魅力一样工作:

在 PrintScreen 方法中,我首先将文件保存到临时目录。 然后调用我的UploadScreenshot()方法,

    private void PrintScreen()
    {
        DateTime utc = DateTime.UtcNow;
        string filename = emp_number + " - " + utc.Ticks.ToString() + ".png";

        Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);

        Graphics graphics = Graphics.FromImage(printscreen as Image);

        graphics.CopyFromScreen(0, 0, 0, 0, printscreen.Size);

        printscreen.Save(runnitsettings + filename, ImageFormat.Png);

        UploadScreenshot(emp_number, runnitsettings + filename);
    }        

在这个 function 中,我从目录中检索文件并将其加载到FileStream ,而不是直接将文件添加到MultipartFormDataContent(); 我创建了一个 function ImageToByte() ,它将首先将文件转换为byte ,然后再转换为Base64String

    private void UploadScreenshot(string employee_id, string filepath)
    {

        string url = baseurl + "upload-screenshot";


        System.IO.FileStream fsstream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        string b64image = ImageToByte(fsstream);
        fsstream.Dispose();
        File.Delete(filepath);

        //I deleted the file after convertion to free some diskspace.

        var multiForm = new MultipartFormDataContent();
        multiForm.Add(new StringContent(employee_id), "emp_number");
        multiForm.Add(new StringContent(b64image), "files");


        //Then I post the data:
        var response = await client.PostAsync(url, multiForm);
        var responseString = await response.Content.ReadAsStringAsync();
    }

图像到字节 Function:

    public static string ImageToByte(FileStream fs)
    {
        byte[] imgBytes = new byte[fs.Length];
        fs.Read(imgBytes, 0, Convert.ToInt32(fs.Length));
        string encodeData = Convert.ToBase64String(imgBytes, Base64FormattingOptions.InsertLineBreaks);

        return encodeData;
    }

在我的 Laravel Controller 中,我这样处理文件:

        $destinationpath = config('filesystems.disks')["private"]["root"]."/screenshots"."/";
        $emp_number = $request["emp_number"];
        $screenshot = $request["files"];
        
        $filename = $emp_number.'-'.date('YmdHis');

        $filePath = $destinationpath.$filename.".png";

        file_put_contents($filePath, base64_decode($screenshot));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM