C# 使用WebAPI上傳檔案實現
阿新 • • 發佈:2019-02-20
第一種通過 Form表單形式
(適用於 JS、Android、IOS等平臺)
/// <summary> /// 上傳檔案 /// </summary> /// <returns></returns> [HttpPost] public string PostFiles() { string result = ""; HttpFileCollection filelist = HttpContext.Current.Request.Files; if (filelist != null && filelist.Count > 0) { for (int i = 0; i < filelist.Count; i++) { HttpPostedFile file = filelist[i]; String Tpath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/"; string filename = file.FileName; string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") ; string FilePath = 儲存路徑+ "\\" + Tpath + "\\"; DirectoryInfo di = new DirectoryInfo(FilePath); if (!di.Exists) { di.Create(); } try { file.SaveAs(FilePath + FileName); result.obj =(Tpath + FileName).Replace("\\", "/"); } catch (Exception ex) { result= "上傳檔案寫入失敗:" + ex.Message; } } } else { result = "上傳的檔案資訊不存在!"; } return result; }
第二種,通過二進位制上傳
/// <summary> /// 檔案上傳 /// </summary> /// <param name="filename">檔名稱</param> /// <param name="FileContent">檔案內容</param> /// <returns></returns> [HttpPost] public string PostFile([FromUri]string filename, [FromBody] byte[] FileContent) { string result = ""; if (FileContent != null) { String Tpath = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/"; string FilePath = 儲存路徑 + "\\" + Tpath+"\\"; String Err = ""; string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); bool upres = FileUtil.WriteFile(FilePath, FileContent, FileName, out Err); if (upres) { result= (Tpath + FileName).Replace("\\", "/"); } else { result= "上傳檔案寫入失敗:" + Err; } } else { result= "上傳的檔案資訊不存在!"; } return result; }
二進位制儲存到檔案的方法
/// <summary> /// 二進位制流寫入檔案 /// </summary> /// <param name="filepath">檔案路徑</param> /// <param name="filecontent">檔案內容</param> /// <param name="FileName">檔名</param> /// <param name="Errmsg">錯誤訊息</param> /// <returns></returns> public static bool WriteFile(string filepath, byte[] filecontent, string FileName,out string Errmsg) { DirectoryInfo di = new DirectoryInfo(filepath); if (!di.Exists) { di.Create(); } FileStream fstream = null; try { fstream = File.Create(filepath + "\\" + FileName, filecontent.Length); fstream.Write(filecontent, 0, filecontent.Length); //二進位制轉換成檔案 } catch (Exception ex) { Errmsg = ex.Message; //丟擲異常資訊 return false; } finally { if(fstream!=null) fstream.Close(); } Errmsg = ""; return true; }