C# WinForm调用net core实现文件上传接口

来自:网络
时间:2024-06-09
阅读:

winform调用API

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 api 接口

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

知识补充

除了上文的方法,小编还为大家整理了一些其他C# WinForm实现文件上传功能的方法,希望对大家有所帮助

C# WinForm 文件上传下载

   /**/ /// <summary>
        /// WebClient上传文件至服务器
        /// </summary>
        /// <param name="localFilePath">文件名,全路径格式</param>
        /// <param name="serverFolder">服务器文件夹路径</param>
        /// <param name="reName">是否需要修改文件名,这里默认是日期格式</param>
        /// <returns></returns>
          public   static   bool  UploadFile( string  localFilePath,  string  serverFolder, bool  reName)
        ... {
            string fileNameExt, newFileName, uriString;
            if (reName)
            ...{
                fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf(".") + 1);
                newFileName = DateTime.Now.ToString("yyMMddhhmmss") + fileNameExt;
            }
            else
            ...{
                newFileName = localFilePath.Substring(localFilePath.LastIndexOf("")+1);
            } 
            if (!serverFolder.EndsWith("/") && !serverFolder.EndsWith(""))
            ...{
                serverFolder = serverFolder + "/";
            }

            uriString = serverFolder + newFileName;   //服务器保存路径
            /**//// 创建WebClient实例
            WebClient myWebClient = new WebClient();
            myWebClient.Credentials = CredentialCache.DefaultCredentials;

            // 要上传的文件
            FileStream fs = new FileStream(newFileName, FileMode.Open, FileAccess.Read);
            BinaryReader r = new BinaryReader(fs);
            try
            ...{
                //使用UploadFile方法可以用下面的格式
                //myWebClient.UploadFile(uriString,"PUT",localFilePath);
                byte[] postArray = r.ReadBytes((int)fs.Length);
                Stream postStream = myWebClient.OpenWrite(uriString, "PUT");
                if (postStream.CanWrite)
                ...{
                    postStream.Write(postArray, 0, postArray.Length);
                }
                else
                ...{
                    MessageBox.Show("文件目前不可写!");
                }
                postStream.Close();
            }
            catch
            ...{
                //MessageBox.Show("文件上传失败,请稍候重试~");
                return false;
            }

            return true;
        }
      

         /**/ /// <summary>
        /// 下载服务器文件至客户端
        /// </summary>
        /// <param name="uri">被下载的文件地址</param>
        /// <param name="savePath">另存放的目录</param>
          public   static   bool  Download( string  uri,  string  savePath)
        ... {
            string fileName;  //被下载的文件名
            if (uri.IndexOf("") > -1)
            ...{
                fileName = uri.Substring(uri.LastIndexOf("") + 1);
            }
            else
            ...{
                fileName = uri.Substring(uri.LastIndexOf("/") + 1);  
            }


            if (!savePath.EndsWith("/") && !savePath.EndsWith(""))
            ...{
                savePath = savePath + "/";
            }

            savePath += fileName;   //另存为的绝对路径+文件名

            WebClient client = new WebClient();
            try
            ...{
                client.DownloadFile(uri, savePath);
            }
            catch
            ...{
                return false;
            }

            return true;
        }  
返回顶部
顶部