上传文件(FTP,云服务,保存本地)
保存本地
/// <summary> /// 上传文件 /// </summary> /// <returns></returns> [HttpPost] public JsonResult UploadFile() { HttpFileCollection files = System.Web.HttpContext.Current.Request.Files; string path = ""; var fileEntitys = new List<FileEntity>(); for (int i = 0; i < files.Count; i++) { string md5 = FileHelper.GetMD5WithFile(files[i]); path = FileHelper.SaveFile(files[i], UniAppVersionUpPath, md5); if (string.IsNullOrWhiteSpace(path)) { return Json("找不到路径", JsonRequestBehavior.AllowGet); } fileEntitys.Add(new FileEntity() { Md5 = md5, Path = path }); } var fpath = fileEntitys.FirstOrDefault(); return Json(new { path = fpath.Path, md5 = fpath.Md5 }, JsonRequestBehavior.AllowGet); }
/// <summary> /// 保存文件 /// </summary> /// <param name="file">文件</param> /// <param name="catalog">文件位置</param> /// <param name="fileName">文件名称</param> /// <returns></returns> public static string SaveFile(HttpPostedFile file, string catalog, string fileName) { if (file.ContentLength != 0) { string absolutePath = HttpContext.Current.Server.MapPath(catalog); if (!Directory.Exists(absolutePath)) { Directory.CreateDirectory(absolutePath); } string fileExten = Path.GetExtension(file.FileName); fileName += fileExten; string fullAbsolutePath = Path.Combine(absolutePath, fileName); file.SaveAs(fullAbsolutePath); if (!catalog.EndsWith("/")) catalog = catalog + "/"; return catalog + fileName; } return null; }
<add key="UniAppVersionUpPath" value="/File/UniAppVersionUpPath/" />
FTP
情况1:服务器禁止外网访问
(为了方便本地测试,单独在服务器发布一个接口。如果测试好了,觉得不想这么麻烦,就用情况2的)
/// <summary> /// 上传文件(只能单个上传,超过2个以上目前有问题) /// </summary> /// <param name="name">模块名称</param> /// <returns></returns> [HttpPost] [Route("UploadFile")] public async Task<IHttpActionResult> UploadFile(string name) { HttpFileCollection files = HttpContext.Current.Request.Files; FailResult f = new FailResult(); if (files.Count == 0) { f = ToolHelper.GetFailResult(Code.NoFile); return Json(f); } var fileEntity = new FileEntity(); if (files.Count > 10) { f = ToolHelper.GetFailResult(Code.FileExcessNumber); return Json(f); } List<FileModel> list = new List<FileModel>(); for (int i = 0; i < files.Count; i++) { string yourMd5 = files.AllKeys[i].ToLower(); fileEntity = FileHelper.FtpObject(files[i], name, yourMd5); if (fileEntity == null) { f = ToolHelper.GetFailResult(Code.NoFile); return Json(f); } list.Add(new FileModel() { Md5 = fileEntity.Md5, Path = fileEntity.Path }); } return Json(list); }
public class FileModel { public string Md5 { get; set; } public string Path { get; set; } }
private static string BaseHost = ConfigurationManager.AppSettings["BaseHost"].ToString(); /// <summary> /// ftp上传对象 /// </summary> /// <param name="file"></param> /// <param name="catalog">文件路径例如 /1/</param> /// <returns></returns> public static FileEntity FtpObject(HttpPostedFile file, string catalog, string fileName) { if (file.ContentLength != 0) { var url = BaseHost+"/File/UploadFile?name=" + catalog+ "&md5="+ fileName+ "&suffix=" + Path.GetExtension(file.FileName); try { using (var ms = new MemoryStream()) { var client = new HttpClient(); var content = new MultipartFormDataContent(); byte[] bytes = GetbyteByHttpPostedFile(file); content.Add(new ByteArrayContent(bytes), "file", fileName); ms.Close(); var result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;//post请求 var resultWords = JsonConvert.DeserializeObject<List<FileEntity>>(result); if (string.IsNullOrWhiteSpace(resultWords[0].Path)) { return null; } return resultWords[0]; } } catch (Exception ex) { return null; } } return null; } /// <summary> /// 下载多个文件,返回临时地址 /// </summary> /// <returns></returns> public static ImgDataModel GetImgObject(string keys, string query = "?x-image-process=image/resize,w_400,limit_0", int minutes = 240) { var resultWords = new ImgDataModel(); try { var keyslist = keys.Split(',').ToList(); keyslist.Remove(""); var serurl = BaseHost + "File/"; var imgUrlModels = new List<ImgUrlModel>(); foreach (var item in keyslist) { var imgUrlModel = new ImgUrlModel() { url = serurl + item, urlWithQuery = serurl + item, time = DateTime.Now.ToString("yyyy-MM-dd") }; imgUrlModels.Add(imgUrlModel); } resultWords.code = 200; resultWords.message = "成功"; resultWords.data = imgUrlModels; return resultWords; } catch (Exception ex) { return resultWords; } } public class ImgDataModel { public int code { get; set; } public string message { get; set; } public List<ImgUrlModel> data { get; set; } } public class ImgUrlModel { /// <summary> /// 全图 /// </summary> public string url { get; set; } /// <summary> /// 缩略图 /// </summary> public string urlWithQuery { get; set; } public string time { get; set; } } public class ObsKeyModel { public int code { get; set; } public string message { get; set; } public DataModel data { get; set; } } public class DataModel { public HeadersModel headers { get; set; } public string url { get; set; } } public class HeadersModel { public string Authorization { get; set; } public string date { get; set; } public string Host { get; set; } }
另外一个服务器的代码
/// <summary> /// 上传文件 /// </summary> /// <param name="name">模块名称</param> /// <param name="md5">MD5</param> /// <param name="name">文件后缀</param> /// <returns></returns> [HttpPost] [Route("UploadFile")] public async Task<IHttpActionResult> UploadFile(string name, string md5, string suffix) { HttpFileCollection files = HttpContext.Current.Request.Files; if (files.Count == 0) { return Json("文件不能为空"); } string path = ""; List<FileModel> list = new List<FileModel>(); for (int i = 0; i < files.Count; i++) { //string md5 = FileHelper.GetMD5WithFile(files[i]); //string yourMd5 = files.AllKeys[i].ToLower(); path = FileHelper.SaveImage(files[i], name, md5, suffix); list.Add(new FileModel() { Md5 = md5, Path = path }); } return Json(list); }
public static string GetMD5WithFile(HttpPostedFile file) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash_byte = md5.ComputeHash(file.InputStream); string str = System.BitConverter.ToString(hash_byte); str = str.Replace("-", ""); return str.ToLower(); } /// <summary> /// 由于接受到的图片没有后缀名,加上 .jpg /// </summary> /// <param name="file"></param> /// <param name="catalog"></param> /// <param name="fileName"></param> /// <param name="suffix"></param> /// <returns></returns> public static string SaveImage(HttpPostedFile file, string catalog, string fileName, string suffix) { if (file.ContentLength != 0) { string fileUrl = "/File/"; catalog = catalog + "/" + DateTime.Now.ToString("yyyy-MM-dd"); if (!catalog.EndsWith("/")) catalog = catalog + "/"; string absolutePath = HttpContext.Current.Server.MapPath(fileUrl + catalog); if (!Directory.Exists(absolutePath)) { Directory.CreateDirectory(absolutePath); } //string fileExten = Path.GetExtension(file.FileName); string fileExten = suffix; if (string.IsNullOrWhiteSpace(fileExten)) { fileName += ".jpg"; } fileName += fileExten; string fullAbsolutePath = Path.Combine(absolutePath, fileName); file.SaveAs(fullAbsolutePath); return catalog + fileName; } return null; }
public class FileModel { public string Md5 { get; set; } public string Path { get; set; } }
情况2:服务器不禁止外网访问
//根据路径获取物理路径 var folder = Server.MapPath(model.fullPath); //获取绝对路径 var fullPath2 = Path.GetFullPath(folder); var resultrMsg = FtpHelper.FtpUpload(fullPath2);
public class FtpHelper { private static string ftpServerIP = ConfigurationManager.AppSettings["FtpUniAppServerIP"].ToString(); private static string ftpUserID = ConfigurationManager.AppSettings["FtpUniAppUserID"].ToString(); private static string ftpPassword = ConfigurationManager.AppSettings["FtpUniAppPassword"].ToString(); private static string FtpUniAppPath = ConfigurationManager.AppSettings["FtpUniAppPath"].ToString(); private static string UniAppVersion = ConfigurationManager.AppSettings["UniAppVersion"].ToString(); /// <summary> /// 上传文件 /// </summary> /// <param name="localFile">文件</param> /// <returns></returns> public static string FtpUpload(string localFile) { //检查目录是否存在,不存在创建 var ftpPath = FtpUniAppPath + "/"; FtpCheckDirectoryExist(ftpPath); try { FileInfo fileInf = new FileInfo(localFile); string uri = string.Format("ftp://{0}/{1}{2}", ftpServerIP, ftpPath, UniAppVersion); FtpWebRequest reqFTP; // 根据uri创建FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型 reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; reqFTP.UsePassive = false;//只需要添加这一句话 // 缓冲大小设置为2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的2kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入 upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); } catch (Exception e) { return e.Message; } return ""; } //判断文件的目录是否存,不存则创建 public static void FtpCheckDirectoryExist(string destFilePath) { string fullDir = FtpParseDirectory(destFilePath); string[] dirs = fullDir.Split('/'); string curDir = "/"; for (int i = 0; i < dirs.Length; i++) { string dir = dirs[i]; //如果是以/开始的路径,第一个为空 if (dir != null && dir.Length > 0) { try { curDir += dir + "/"; FtpMakeDir(curDir); } catch (Exception ex) { } } } } public static string FtpParseDirectory(string destFilePath) { return destFilePath.Substring(0, destFilePath.LastIndexOf("/")); } //创建目录 public static Boolean FtpMakeDir(string localFile) { string uri = string.Format("ftp://{0}{1}", ftpServerIP, localFile); FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); req.Credentials = new NetworkCredential(ftpUserID, ftpPassword); req.Method = WebRequestMethods.Ftp.MakeDirectory; try { FtpWebResponse response = (FtpWebResponse)req.GetResponse(); response.Close(); } catch (Exception) { req.Abort(); return false; } req.Abort(); return true; } }
<add key="FtpUniAppServerIP" value="127.0.0.1" /> <add key="FtpUniAppUserID" value="FtpUserttt" /> <add key="FtpUniAppPassword" value="Ftp1234567897" /> <add key="FtpUniAppPath" value="UniAppTest" />
云服务
(1)上传方法
/// <summary> /// 上传文件(单个上传,可以执行修改成多个上传) /// </summary> /// <param name="name">模块名称</param> /// <returns></returns> [HttpPost] [Route("UploadFile")] public async Task<IHttpActionResult> UploadFile(string name) { HttpFileCollection files = HttpContext.Current.Request.Files; FailResult f = new FailResult(); if (files.Count == 0) { f = ToolHelper.GetFailResult(Code.NoFile); return Json(f); } string path = ""; List<FileModel> list = new List<FileModel>(); if (files.Count > 10) { f = ToolHelper.GetFailResult(Code.FileExcessNumber); return Json(f); } for (int i = 0; i < files.Count; i++) { string yourMd5 = files.AllKeys[i].ToLower(); path = FileHelper.PostObject(files[i], name, yourMd5); if (string.IsNullOrWhiteSpace(path)) { f = ToolHelper.GetFailResult(Code.NoFile); return Json(f); } list.Add(new FileModel() { Md5 = yourMd5, Path = path }); } return Json(list); }
public class FileModel { public string Md5 { get; set; } public string Path { get; set; } }
(2)查看图片
var Item6Img = data.SetRemarkImage == "" ? new List<string>() : data.SetRemarkImage.SplitNew(',').Select(u => StaticConstant.BaseHost + u).ToList();
(3)调到方法FileHelper
public class FileHelper { private static ILog Logger = LogManager.GetLogger(nameof(FileHelper)); private static string UploadFileUrlPath = ConfigurationManager.AppSettings["UploadFileUrlPath"].ToString(); /// <summary> /// put 上传单个文件,返回临时密钥 /// </summary> /// <returns></returns> public static ObsKeyModel PutObject(string md5) { var resultWords = new ObsKeyModel(); try { var url = $"{UploadFileUrlPath}/Obs/" + md5; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "PUT"; request.ContentType = "application/json"; request.ContentLength = 0; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { var result = reader.ReadToEnd(); resultWords = JsonConvert.DeserializeObject<ObsKeyModel>(result); return resultWords; } } catch (Exception ex) { return resultWords; } } /// <summary> /// Post 上传对象 /// </summary> /// <param name="fileName"></param> /// <param name="catalog">文件路径例如 /1/</param> /// <param name="file"></param> /// <returns></returns> public static string PostObject(HttpPostedFile file, string catalog, string fileName) { if (file.ContentLength != 0) { if (!catalog.EndsWith("/")) catalog = catalog + "/"; catalog = catalog + DateTime.Now.ToString("yyyy-MM-dd") + "/"; string fileExten = Path.GetExtension(file.FileName); if (string.IsNullOrWhiteSpace(fileExten)) { fileName += ".jpg"; } fileName += fileExten; fileName = catalog + fileName; var url = $"{UploadFileUrlPath}/Obs/{HttpUtility.UrlEncode(fileName)}"; try { using (var ms = new MemoryStream()) { var client = new HttpClient(); var content = new MultipartFormDataContent(); byte[] bytes = GetbyteByHttpPostedFile(file); content.Add(new ByteArrayContent(bytes), "file", fileName); ms.Close(); var result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;//post请求 var resultWords = JsonConvert.DeserializeObject<SuccessResult>(result); if (resultWords.Code == 0) { return null; } return fileName; } } catch (Exception ex) { return null; } } return null; } /// <summary> /// 下载多个文件,返回临时地址 /// </summary> /// <returns></returns> public static ImgDataModel GetImgObject(string keys, string query = "?x-image-process=image/resize,w_400,limit_0", int minutes = 240) { var resultWords = new ImgDataModel(); try { var url = $"{UploadFileUrlPath}/Obs"; var client = new HttpClient(); var keyslist = keys.Split(',').ToList(); keyslist.Remove(""); var param = new { keys = keyslist, query = query, minutes = minutes }; var jStr = JsonConvert.SerializeObject(param); StringContent stringContent = new StringContent(jStr); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" }; var result = client.PostAsync(url, stringContent).Result;//post请求 var result2 = result.Content.ReadAsStringAsync().Result; resultWords = JsonConvert.DeserializeObject<ImgDataModel>(result2); return resultWords; } catch (Exception ex) { return resultWords; } } /// <summary> /// 根据文件返回二进制 /// </summary> /// <param name="file"></param> /// <returns></returns> public static byte[] GetbyteByHttpPostedFile(HttpPostedFile file) { var stream = file.InputStream; var readBuffer = new byte[stream.Length]; stream.Read(readBuffer, 0, readBuffer.Length); stream.Seek(0, SeekOrigin.Begin); return readBuffer; } public static string getFileBase64(string fileName) { FileStream filestream = new FileStream(fileName, FileMode.Open); byte[] arr = new byte[filestream.Length]; filestream.Read(arr, 0, (int)filestream.Length); string baser64 = Convert.ToBase64String(arr); filestream.Close(); return baser64; } } public class ImgDataModel { public int code { get; set; } public string message { get; set; } public List<ImgUrlModel> data { get; set; } } public class ImgUrlModel { /// <summary> /// 全图 /// </summary> public string url { get; set; } /// <summary> /// 缩略图 /// </summary> public string urlWithQuery { get; set; } public string time { get; set; } } public class ObsKeyModel { public int code { get; set; } public string message { get; set; } public DataModel data { get; set; } } public class DataModel { public HeadersModel headers { get; set; } public string url { get; set; } } public class HeadersModel { public string Authorization { get; set; } public string date { get; set; } public string Host { get; set; } }