第一种通过 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; }
共有条评论 网友评论