.NET Core 文件上传、下载、文件流转换
生活随笔
收集整理的這篇文章主要介紹了
.NET Core 文件上传、下载、文件流转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
通過Webapi下載文件:
//前端請求預覽或下載文件(微信小程序也一樣)[HttpGet]public async Task<IActionResult> DownloadYFPreview([FromQuery] string openId, string dbName, string orderName, string id){if (openId == null || dbName == null || orderName == null)return UnprocessableEntity();//從sql server數據庫獲取下載的文件二進制內容PreviewInfoModel infoModel = await _orderApproval.DownloadPreview(openId, dbName, orderName, id);if (infoModel == null)return null;string lastinfo = infoModel.name.Split('.')[1];if (lastinfo.Equals("docx"))lastinfo = "doc";else if (lastinfo.Equals("pptx"))lastinfo = "ppt";else if (lastinfo.Equals("xlsx"))lastinfo = "xls";//獲取文件的contentType(通過后綴名從json文件中匹配contentType)var item = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build().GetSection("contenttype").GetSection(lastinfo).Value;//下載文件return File(infoModel.buffer, item, infoModel.name);}前端附件預覽:
//附件預覽 preview: function (id) {var _this = this;var path = _this.prefix + "/FindOne/" + id;hzyAdmin.httpPost(path, {}, function (r) {if (r.code !== 1) return;//文件流var imageBytes = r.data.model.cim002;//contentTypevar fileType = r.data.model.cim004;var myFile = _this.createFile(imageBytes, fileType);var urll = window.URL.createObjectURL(myFile);window.open(urll);}); }, //轉換文件流 createFile: function (urlData, fileType) {var bytes = window.atob(urlData),n = bytes.length,u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bytes.charCodeAt(n);}return new Blob([u8arr], { type: fileType }); }前端elementUi上傳附件:
<div class="col-sm-12"><el-upload class="upload-demo"@*上傳地址*@action="/Admin/rgwimg/uploadinfo"@*其它請求參數*@:data={id:this.idx,name:this.name}:on-preview="handlePreview":on-remove="handleRemove":before-remove="beforeRemove"multiple:on-exceed="handleExceed":on-success="success"@*選擇之后立即上傳*@:auto-upload="true":show-file-list="false"><el-button size="large" type="primary">點擊上傳</el-button></el-upload> </div>后端接收上傳附件保存到sql server中:
?
微信小程序附件預覽:
//前端代碼 <view class="rightopera" data-idx="{{item.docId}}" bindtap="download" >//預覽代碼download(e){const id = e.currentTarget.dataset.idx;let tokens=app.globalData.token;wx.downloadFile({url: 'https://192.168.0.127:44349/api/OrderApproval/DownloadYFPreview?dbName='+this.data.dbname+'&orderName='+this.data.ordername+'&openId='+app.globalData.openid+'&id='+id,header:{"Authorization": 'Bearer ' +tokens},success (res) {//只要服務器有響應數據,就會把響應內容寫入文件并進入 success 回調,業務需要自行判斷是否下載到了想要的內容if (res.statusCode === 200) {var filePath=res.tempFilePath;console.log(filePath);var reg = RegExp(/.png/);if(filePath.match(reg)){var img=[];img.push(filePath);wx.previewImage({current: img[0], //當前預覽的圖片urls: img //所有要預覽的圖片})}else{wx.openDocument({filePath: filePath,success: function (res) {console.log('打開文檔成功')}})}}}})}小程序前端附件上傳:
//前端提交布局代碼 <view class="bottomBtn" bindtap="submitForm">提交</view> //附件提交代碼submitForm(e) {if (this.data.details == "") {wx.showToast({title: "請輸入評論",icon: "loading",duration: 1000});return;}let time = new Date().getTime();let tokens = app.globalData.token;this.uploadFile(time, tokens).then(res => {if (res.statusCode == "401") {request.getLoginInfo(app.globalData.openid).then(res => {tokens = res.data.token;this.uploadFile(time, tokens).then(res => {wx.showToast({title: "網絡異常,請稍后重試",icon: "loading",duration: 1000});});});} else if (res.statusCode == "200") {this.backprevious();} else {wx.showToast({title: "網絡異常,請稍后重試",icon: "loading",duration: 1000});}});},uploadFile(time, tokens) {var result = true;var length = this.data.images.length;return new Promise((resolve, reject) => {for (let i = 0; i < length; i++) {if (!result) break;wx.uploadFile({url: "https://www.baidu.com/api/OrderApproval/UploadImg",filePath: this.data.images[i],name: "file",header: {"Content-Type": "multipart/form-data;application/json;",Authorization: "Bearer " + tokens},formData: {orderid: this.data.orderid,openid: app.globalData.openid,content: this.data.details,times: time},success: function(res) {if (res.statusCode == "401") {result = false;resolve(res);}if (i == length - 1 && res.statusCode == "200") {resolve(res);}},fail: function(err) {result = false;reject(err);},complete: function(res) {wx.showToast({title: "上傳" + i + " code:" + res.statusCode+" errMsg:"+res.errMsg,icon: "loading",duration: 1000});}});}});}后端接收附件保存到服務器指定文件夾:
/// <summary>/// 上傳圖片,通過Form表單提交/// </summary>/// <returns></returns>[HttpPost]//[DisableRequestSizeLimit] //不限制請求頭model的大小//[RequestSizeLimit(100_000_000)] //請求大小值為100,000,000 字節public async Task<IActionResult> UploadImg(){commentModel commentModel = new commentModel();if (Request.Form.TryGetValue("orderid", out StringValues orderid))commentModel.orderid = orderid.ToString();if (Request.Form.TryGetValue("openid", out StringValues openid))commentModel.openid = openid.ToString(); if (Request.Form.TryGetValue("content", out StringValues content))commentModel.content = content.ToString();if (Request.Form.TryGetValue("times", out StringValues times))commentModel.times = times.ToString();var sx = Request.Form.Files["file"];var now = DateTime.Now;var pathdate = now.ToString("yyyy") + now.ToString("MM") + now.ToString("dd");//文件存儲路徑var filePath = string.Format("/Uploads/{0}/{1}/{2}/", now.ToString("yyyy"), now.ToString("MM"), now.ToString("dd"));//獲取當前web目錄var webRootPath = Directory.GetCurrentDirectory();if (!Directory.Exists(webRootPath + filePath)){Directory.CreateDirectory(webRootPath + filePath);}try{var fileExtension = Path.GetExtension(sx.FileName);var strDateTime = DateTime.Now.ToString("yyMMddhhmmssfff"); //取得時間字符串var strRan = Convert.ToString(new Random().Next(100, 999)); //生成三位隨機數var saveName = strDateTime + strRan + fileExtension;string path = webRootPath + filePath + pathdate + saveName;using (FileStream fs = System.IO.File.Create(path)){sx.CopyTo(fs);fs.Flush();}commentModel.picAddress = pathdate + saveName;bool result = await _orderApproval.SavePics(commentModel);if (!result)return BadRequest("保存失敗,請稍后重試");return Ok();}catch (Exception ex){return BadRequest();}}流轉換:
//byte[]直接轉換內存流,供下載使用 byte[] buffer=new byte[1000]; MemoryStream ms = new MemoryStream(buffer); ms.Write(buffer, 0, buffer.Length); ms.Position = 0; ms.Seek(0, SeekOrigin.Begin); return new FileContentResult(buffer, "image/png"); //FileStream轉為MemoryStream,再轉為byte[] byte[] StreamToFile(FileStream fileStream, MemoryStream memoryStream){byte[] files = new byte[0];byte[] fileBytes = new byte[fileStream.Length];fileStream.Read(fileBytes, 0, (int)fileStream.Length);memoryStream.Write(fileBytes, 0, (int)fileStream.Length);files= memoryStream.ToArray();fileStream.Close();memoryStream.Close();return files;}讀取網絡共享文件:
參考:https://www.cjavapy.com/article/395/ byte[] files=new byte[0]; var folder = new SmbFile("smb://Administrator:123@192.168.0.84/YFATTACH/0010000132.001"); if (!folder.Exists())return files; //獲取可讀的流 var readStream = folder.GetInputStream(); //獲取 bytes. ((Stream)readStream).CopyTo(memStream);//Dispose可讀的流。 readStream.Dispose(); files= memoryStream.ToArray(); return files;把網絡共享文件讀到本地:
byte[] ReadFile(string path,string fileId,string fileName){byte[] files = new byte[0];string filepath = Directory.GetCurrentDirectory() + "/Files/";string oldFileName = $"{filepath}/{fileId}";string newFileName = $"{filepath}/{fileName}";FileStream fileStream = null;//判斷文件是否存在bool isExists = File.Exists($"{filepath}/{fileName}");if (isExists)//若存在,則讀取文件到內存fileStream = new FileStream($"{filepath}/{fileName}", FileMode.Open);//創建讀取緩存var memStream = new MemoryStream();if (!isExists){ //var folder = new SmbFile("smb://Administrator:123@192.168.0.84/YFATTACH/0010000132.001");var folder = new SmbFile($"smb://{path}");if (!folder.Exists())return files;//獲取可讀的流。var readStream = folder.GetInputStream();//獲取 bytes.((Stream)readStream).CopyTo(memStream);//Dispose可讀的流。readStream.Dispose();if (!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}string filesName = filepath + folder.GetName();using (FileStream fls = System.IO.File.Create(filesName)){//內存流轉為文件流,并寫入磁盤fls.Write(memStream.ToArray(), 0, memStream.ToArray().Length);fls.Close();}//重命名文件名及擴張名File.Copy(oldFileName, newFileName);fileStream = new FileStream($"{filepath}/{fileName}", FileMode.Open);if (fileStream.Length > 0)files= StreamToFile(fileStream, memStream);}elsefiles= StreamToFile(fileStream, memStream);//刪除指定文件File.Delete(oldFileName);File.Delete(newFileName);return files;}byte[] StreamToFile(FileStream fileStream, MemoryStream memoryStream){byte[] files = new byte[0];byte[] fileBytes = new byte[fileStream.Length];fileStream.Read(fileBytes, 0, (int)fileStream.Length);memoryStream.Write(fileBytes, 0, (int)fileStream.Length);files= memoryStream.ToArray();fileStream.Close();memoryStream.Close();return files;}謝謝打賞:
? ?
總結
以上是生活随笔為你收集整理的.NET Core 文件上传、下载、文件流转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 制作PHP动态网页软件,使用PHP制作动
- 下一篇: ABB低压干式电容器CLMD系列