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; }
到此这篇关于c# winform调用net core实现文件上传接口的文章就介绍到这了,更多相关c#文件上传内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论