Winform Call API
private void button3_Click(object sender, EventArgs e) { var uriAddress = "https://localhost:44381/file/api/VoiceASRT/WavConvertFile"; //var uploadfilePath = "G:\\BaiduNetdiskDownload\\JJ Lin - Unfortunately, there is no if.wav"; var uploadfilePath = "H:\\Installation Steps.txt"; //UploadFile(uriAddress, uploadfilePath); updateFile(uriAddress, uploadfilePath); } //Test OK /// <summary> /// Upload a single file to the server 413 is an error that the file is too large. By default, it will cause an error to be reported if it is greater than 4M. You need to modify the relevant configuration /// public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) /// The file upload interface call test is successful /// </summary> /// <param name="uriAddress">URI that receives file resources, for example: http://xxxx/</param> /// <param name="filePath">The resource file to be sent, for example: @"D:\workspace\WebService related.doc</param> /// <returns> Returns the relative path to save the file, for example: "upload/" or an error returns ""</returns> private string UploadFile(string uriAddress, string filePath) { //Use WebClient webClient = new (); = ; try { byte[] responseArray = (uriAddress, "POST", filePath); string savePath = (responseArray); return savePath; } catch (Exception ex) { return ""; } } /// <summary> /// Test OK /// public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) /// The file upload interface call test is successful /// </summary> /// <param name="url"></param> /// <param name="filePath"></param> public void updateFile(string url, string filePath) { try { string fileName_key_ = "kekename\\" + (filePath); string access_token = "fz434507768345eb7a8e97897"; byte[] fileContentByte = new byte[1024]; // File content binary #region Convert file to binary FileStream fs = new FileStream(filePath, , ); fileContentByte = new byte[]; // Binary file (fileContentByte, 0, Convert.ToInt32()); (); #endregion #region Define the content in the request body and convert it into binary *************************************************** Key: Splicing parameters ********************************************************* string boundary = "ceshi"; string Enter = "\r\n"; //string modelIdStr = "--" + boundary + Enter // + "Content-Disposition: form-data; name=\"modelId\"" + Enter + Enter // + modelId + Enter; string fileContentStr = "--" + boundary + Enter + "Content-Type:application/octet-stream" + Enter + "Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"" + Enter + Enter; string updateTimeStr = Enter + "--" + boundary + Enter + "Content-Disposition: form-data; name=\"key\"" + Enter + Enter + fileName_key_; string encryptStr = Enter + "--" + boundary + Enter + "Content-Disposition: form-data; name=\"access_token\"" + Enter + Enter + access_token + Enter + "--" + boundary + "--"; // var modelIdStrByte = Encoding.(modelIdStr);//modelId all string binary var fileContentStrByte = Encoding.(fileContentStr);//fileContent some binary information such as name (not including the file itself) var updateTimeStrByte = Encoding.(updateTimeStr);// updateTime All string binary var encryptStrByte = Encoding.(encryptStr);//encrypt all string binary #endregion ************************************************ Key: Splicing parameters ************************************************************ HttpWebRequest request = (HttpWebRequest)(url); = "POST"; = "multipart/form-data;boundary=" + boundary; Stream myRequestStream = ();//Define the request flow #region Writes each binary in an order to the request stream modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr // (modelIdStrByte, 0, ); (fileContentStrByte, 0, ); (fileContentByte, 0, ); (updateTimeStrByte, 0, ); (encryptStrByte, 0, ); #endregion HttpWebResponse response = (HttpWebResponse)();//send Stream myResponseStream = ();//Get the return value StreamReader myStreamReader = new StreamReader(myResponseStream, ("utf-8")); string retString = (); (); (); JObject jo = (JObject)(retString); string Code = jo["code"].ToString(); string desc = jo["desc"].ToString(); string data = jo["data"].ToString(); JObject datajson = (JObject)(data); string file_url_ = datajson["file_url"].ToString(); //if (Code == "0") //{ // UpdateImgSerialInfo("5", file_url_); //} //else //{ // ("Uploading the image failed, the interface returns: " + desc); //} } catch (Exception ex) { //("An error occurred when uploading the image: " + ex); } }
net core api interface
/// <summary> /// Wav file translation /// </summary> /// <param name="files"></param> /// <returns></returns> [HttpPost] public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) { try { if (files != null && > 0) { string fileName = files[0].Name; if ((fileName).Equals("wav")) { int MaxSize = (["MaxSize"]); if (files[0].Length <= MaxSize)//Check file size { //&& ().Equals("wav") if (_speechRecognizer != null) { // Read wave data from the cache and send it to voice recognition //Stream waveMemStream = wavfile; string UploadFilePath = ["UploadFilePath"]; string cdipath = (); string upfileDirePath = cdipath + UploadFilePath + "WavFiles\\" + fileName; using (FileStream fileStream = new (upfileDirePath, , , , MaxSize)) { await files[0].CopyToAsync(fileStream); WaveData wav = (fileStream); AsrtApiResponse rsp = await _speechRecognizer.RecogniteAsync(, , , ); AsrtResult result = new AsrtResult((string), true, , ); ("WavConvert").Info("WavConvert interface handles requests:" + fileName + "Result of the document:" + ); return Success(, "Successful Translation"); } } else { return Error("ASRT server API initialization failed"); } } else { return Error("The file is too big"); } } else { return Error("Voice file type error"); } } else { return Error("Voice file type error"); } } catch ( ex) { ("LawcaseEvidenceUploadFileAsync").Info("Report an error" + ); return Error("Transfer error:" + ); } }
Knowledge Supplement
C# WinForm file upload and download
/**/ /// <summary> /// WebClient uploads files to the server /// </summary> /// <param name="localFilePath">File name, full path format</param> /// <param name="serverFolder">Server folder path</param> /// <param name="reName">Does the file name need to be modified? The default is the date format</param> /// <returns></returns> public static bool UploadFile( string localFilePath, string serverFolder, bool reName) ... { string fileNameExt, newFileName, uriString; if (reName) ...{ fileNameExt = ((".") + 1); newFileName = ("yyMMddhhmmss") + fileNameExt; } else ...{ newFileName = (("")+1); } if (!("/") && !("")) ...{ serverFolder = serverFolder + "/"; } uriString = serverFolder + newFileName; //Server save path /**//// Create a WebClient instance WebClient myWebClient = new WebClient(); = ; // File to upload FileStream fs = new FileStream(newFileName, , ); BinaryReader r = new BinaryReader(fs); try ...{ //Use the UploadFile method to use the following format //(uriString,"PUT",localFilePath); byte[] postArray = ((int)); Stream postStream = (uriString, "PUT"); if () ...{ (postArray, 0, ); } else ...{ ("The file is not allowed to be written at the moment!"); } (); } catch ...{ //("File upload failed, please try again~"); return false; } return true; } /**/ /// <summary> /// Download the server file to the client /// </summary> /// <param name="uri">File address to be downloaded</param> /// <param name="savePath">Save directory</param> public static bool Download( string uri, string savePath) ... { string fileName; //The file name that was downloaded if (("") > -1) ...{ fileName = (("") + 1); } else ...{ fileName = (("/") + 1); } if (!("/") && !("")) ...{ savePath = savePath + "/"; } savePath += fileName; //Absolute path + file name of Save As WebClient client = new WebClient(); try ...{ (uri, savePath); } catch ...{ return false; } return true; }
This is the article about C# WinForm calling net core to implement the file upload interface. For more related C# file upload content, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!