C# WinForm 调用net core文件上传接口
调用
private void button3_Click(object sender, EventArgs e) { var uriAddress = "https://localhost:44381/file/api/VoiceASRT/WavConvertFile"; //var uploadfilePath = "G:\\BaiduNetdiskDownload\\林俊杰 - 可惜没如果.wav"; var uploadfilePath = "H:\\安装步骤.txt"; //UploadFile(uriAddress, uploadfilePath); updateFile(uriAddress, uploadfilePath); } //测试OK /// <summary> /// 单个文件上传至服务器 413是文件太大的错,默认应该是大于4M就会报错,要修改相关配置 /// public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) /// 文件上传接口调用测试成功 /// </summary> /// <param name="uriAddress">接收文件资源的URI, 例如: http://xxxx/Upload.aspx</param> /// <param name="filePath">要发送的资源文件, 例如: @"D:\workspace\WebService 相关.doc</param> /// <returns>返回文件保存的相对路径, 例如: "upload/xxxxx.jpg" 或者出错返回 ""</returns> private string UploadFile(string uriAddress, string filePath) { //利用 WebClient System.Net.WebClient webClient = new System.Net.WebClient(); webClient.Credentials = System.Net.CredentialCache.DefaultCredentials; try { byte[] responseArray = webClient.UploadFile(uriAddress, "POST", filePath); string savePath = System.Text.Encoding.ASCII.GetString(responseArray); return savePath; } catch (Exception ex) { return ""; } } /// <summary> /// 测试OK /// public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) /// 文件上传接口调用测试成功 /// </summary> /// <param name="url"></param> /// <param name="filePath"></param> public void updateFile(string url, string filePath) { try { string fileName_key_ = "kekename\\" + Path.GetFileName(filePath); string access_token = "fz434507768345eb7a8e97897"; byte[] fileContentByte = new byte[1024]; // 文件内容二进制 #region 将文件转成二进制 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); fileContentByte = new byte[fs.Length]; // 二进制文件 fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length)); fs.Close(); #endregion #region 定义请求体中的内容 并转成二进制 ********************************************************* 重点 :拼接参数 ******************************************************* 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.UTF8.GetBytes(modelIdStr);//modelId所有字符串二进制 var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr);//fileContent一些名称等信息的二进制(不包含文件本身) var updateTimeStrByte = Encoding.UTF8.GetBytes(updateTimeStr);//updateTime所有字符串二进制 var encryptStrByte = Encoding.UTF8.GetBytes(encryptStr);//encrypt所有字符串二进制 #endregion ********************************************************* 重点 :拼接参数 ******************************************************* HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "multipart/form-data;boundary=" + boundary; Stream myRequestStream = request.GetRequestStream();//定义请求流 #region 将各个二进制 安顺序写入请求流 modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr // myRequestStream.Write(modelIdStrByte, 0, modelIdStrByte.Length); myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length); myRequestStream.Write(fileContentByte, 0, fileContentByte.Length); myRequestStream.Write(updateTimeStrByte, 0, updateTimeStrByte.Length); myRequestStream.Write(encryptStrByte, 0, encryptStrByte.Length); #endregion HttpWebResponse response = (HttpWebResponse)request.GetResponse();//发送 Stream myResponseStream = response.GetResponseStream();//获取返回值 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); JObject jo = (JObject)JsonConvert.DeserializeObject(retString); string Code = jo["code"].ToString(); string desc = jo["desc"].ToString(); string data = jo["data"].ToString(); JObject datajson = (JObject)JsonConvert.DeserializeObject(data); string file_url_ = datajson["file_url"].ToString(); //if (Code == "0") //{ // UpdateImgSerialInfo("5", file_url_); //} //else //{ // SalMessage.Error("上传图片失败,接口返回:" + desc); //} } catch (Exception ex) { //SalMessage.Error("上传图片出错:" + ex); } }
net core 接口
/// <summary> /// Wav 文件转写 /// </summary> /// <param name="files"></param> /// <returns></returns> [HttpPost] public async Task<AjaxResult> WavConvertFile([FromForm] IFormFileCollection files) { try { if (files != null && files.Count > 0) { string fileName = files[0].Name; if (Path.GetExtension(fileName).Equals("wav")) { int MaxSize = int.Parse(LD.Code.ConfigurationManager.UpFileOptions["MaxSize"]); if (files[0].Length <= MaxSize)//检查文件大小 { //&& Path.GetExtension(wavfile.Name).Equals("wav") if (_speechRecognizer != null) { // 从缓存中读取wave数据,并送去语音识别 //Stream waveMemStream = wavfile; string UploadFilePath = LD.Code.ConfigurationManager.UpFileOptions["UploadFilePath"]; string cdipath = Directory.GetCurrentDirectory(); string upfileDirePath = cdipath + UploadFilePath + "WavFiles\\" + fileName; using (FileStream fileStream = new System.IO.FileStream(upfileDirePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite, MaxSize)) { await files[0].CopyToAsync(fileStream); WaveData wav = SDK.ReadWaveDatas(fileStream); AsrtApiResponse rsp = await _speechRecognizer.RecogniteAsync(wav.byteWavs, wav.sampleRate, wav.channels, wav.byteWidth); AsrtResult result = new AsrtResult((string)rsp.Result, true, rsp.StatusCode, rsp.StatusMessage); LogFactory.GetLogger("WavConvert").Info("WavConvert 接口处理请求:" + fileName + "文件的转写结果:" + result.Text); return Success(result.Text, "转写成功"); } } else { return Error("ASRT 服务器API初始化失败"); } } else { return Error("文件太大了"); } } else { return Error("语音文件类型错误"); } } else { return Error("语音文件类型错误"); } } catch (System.Exception ex) { LogFactory.GetLogger("LawcaseEvidenceUploadFileAsync").Info("报错" + ex.Message); return Error("转写报错:" + ex.Message); } }