webapi批量上传照片(form-data)
#region 上传文件接口 /// <summary> /// 上传文件 /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpPost] [Route("postFile")] public Task<HttpResponseMessage> PostFile(HttpRequestMessage request) { // 是否请求包含multipart/form-data。 if (!request.Content.IsMimeMultipartContent()) { Logger.Error("上传格式不是multipart/form-data"); throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } if (!ModelState.IsValid) { Logger.Error("PostFile参数错误。"); throw new HttpResponseException(HttpStatusCode.BadRequest); } var root = AppDomain.CurrentDomain.BaseDirectory; var provider = new MultipartFormDataStreamProvider(root); // 阅读表格数据并返回一个异步任务. var task = request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t => { HttpResponseMessage response = null; if (t.IsFaulted || t.IsCanceled) { Logger.Info("PostFile is faulted or canceled: " + t.Exception.Message); response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception); } else { // string dicName = DateTime.Now.ToString("yyyyMMdd"); string ftpPath = CreateFolderAtFtp(modelName, dicName); long visitInfoId = 0; if (!long.TryParse(provider.FormData["visitInfoId"], out visitInfoId)) { response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, "参数格式错误!"); } else { // 多文件上传 foreach (var file in provider.FileData) { string fileName = file.Headers.ContentDisposition.FileName; if (fileName.StartsWith("\"") && fileName.EndsWith("\"")) { fileName = fileName.Trim('"'); } if (fileName.Contains(@"/") || fileName.Contains(@"\")) { fileName = Path.GetFileName(fileName); } String ext = System.IO.Path.GetExtension(fileName); var newFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") + ext; File.Copy(file.LocalFileName, Path.Combine(root, newFileName)); FileInfo img = new FileInfo(Path.Combine(root, newFileName)); FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpAddress + ftpPath + "/" + newFileName)); reqFTP.Credentials = new NetworkCredential(username, password); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = img.Length; int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; FileStream fs = img.OpenRead(); try { Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); img.Delete(); File.Delete(file.LocalFileName); } catch (Exception ex) { Logger.Error("PostFile()服务器错误", ex); response = request.CreateResponse(HttpStatusCode.InternalServerError, new { error = "文件上次失败,请与管理员联系!" }); } var entity = new VisitPiction { CustomerVisitInfoId = visitInfoId, Createtime = DateTime.Now, Path = httpAddress + ftpPath + "/" + newFileName }; customerService.AddVisitPic(entity); } response = request.CreateResponse(HttpStatusCode.OK, new { success = true }); } } return response; }); return task; } public string CreateFolderAtFtp(string modelName, string dicName) { string ftpPath = string.Empty; if (!string.IsNullOrEmpty(modelName)) { //检测是否有该企业的模块文件夹 bool isExist = IsDirectoryExist(ftpAddress + modelName + "/"); if (!isExist) { string dic = CreateDirectoryAtFtp(modelName, "", ""); if (string.IsNullOrEmpty(dic)) { throw new Exception("创建文件夹失败"); } } ftpPath += "/" + modelName; } if (!string.IsNullOrEmpty(dicName)) { //检测是否有该企业模块下的子文件夹 bool isExist = IsDirectoryExist(ftpAddress + modelName + "/" + dicName + "/"); if (!isExist) { string dic = CreateDirectoryAtFtp(modelName, dicName, ""); if (string.IsNullOrEmpty(dic)) { throw new Exception("创建文件夹失败"); } } ftpPath += "/" + dicName; } return ftpPath; } /// <summary> /// 判斷指定得路徑是否存在于ftp上 /// </summary> /// <param name="fileFullPath"></param> public bool IsDirectoryExist(string fullDirectory) { if (!fullDirectory.EndsWith("/")) fullDirectory += "/"; bool result = false; //執行ftp命令 活動目錄下所有文件列表 Uri uriDir = new Uri(fullDirectory); WebRequest listRequest = WebRequest.Create(uriDir); listRequest.Method = WebRequestMethods.Ftp.ListDirectory; listRequest.Credentials = new NetworkCredential(username, password); //listRequest.KeepAlive = false; //執行一個命令后關閉連接 WebResponse listResponse = null; try { listResponse = listRequest.GetResponse(); result = true; } catch { result = false; } finally { if (listResponse != null) listResponse.Close(); } return result; } /// <summary> /// 在FTP創建一個新文件夾 /// </summary> /// <param name="root">要在那个路径下创建文件夹</param> /// <param name="DicLayer3"></param> /// <returns>创建成功的ftp上的全路径</returns> private string CreateDirectoryAtFtp(string DicLayer1, string DicLayer2, string DicLayer3) { try { //在ftp上的路径 string ftpPath = DicLayer1; if (!string.IsNullOrEmpty(DicLayer2)) { ftpPath += "/" + DicLayer2; } if (!string.IsNullOrEmpty(DicLayer3)) { ftpPath += "/" + DicLayer3; } Uri uri = new Uri(ftpAddress + ftpPath); FtpWebRequest listRequest = (FtpWebRequest)FtpWebRequest.Create(uri); if (!IsDirectoryExist(uri.ToString())) { listRequest.Method = WebRequestMethods.Ftp.MakeDirectory; } else { CreateFullDirectoryAtFtp(uri.ToString()); listRequest.Method = WebRequestMethods.Ftp.ListDirectory; } listRequest.Credentials = new NetworkCredential(username, password); listRequest.KeepAlive = false; //執行一個命令后關閉連接 FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); string fullPath = ftpAddress + ftpPath + "/"; Stream write = GetWriteStream(fullPath + "ftpPath.ini"); //在ftp上創建文件 byte[] context = System.Text.Encoding.Default.GetBytes("ftpPath=" + ftpPath); write.Write(context, 0, context.Length); write.Close(); return ftpPath; // 返回創建目錄路徑 } catch (Exception ex) { Logger.Error("创建文件夹失败" + ex.Message); return String.Empty; } } /// <summary> /// 在ftp上創建文件夾(若目錄不存在則依序創建)。 /// </summary> /// <param name="directoryName"></param> public void CreateFullDirectoryAtFtp(string directoryPath) { Uri uriDir = new Uri(directoryPath); directoryPath = uriDir.AbsolutePath; directoryPath = directoryPath.Replace(@"\", "/"); directoryPath = directoryPath.Replace("//", "/"); string[] aryDirctoryName = directoryPath.Split('/'); string realPath = ""; realPath = ftpAddress; for (int i = 0; i < aryDirctoryName.Length; i++) { if (aryDirctoryName[i] != String.Empty) { realPath = realPath + "/" + aryDirctoryName[i]; if (!IsDirectoryExist(realPath)) { CreateDirectoryAtFtp(realPath); } } } } /// <summary> /// 在ftp上創建文件夾,用於對zip文檔得解壓。 /// </summary> /// <param name="directoryName"></param> public void CreateDirectoryAtFtp(string directoryName) { try { Uri uri = new Uri(directoryName); FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(uri); listRequest.Method = WebRequestMethods.Ftp.MakeDirectory; listRequest.Credentials = new NetworkCredential(username, password); listRequest.KeepAlive = false; //執行一個命令后關閉連接 FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse(); } catch (Exception ex) { throw ex; } } public Stream GetWriteStream(string fileFullName) { FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(new Uri(fileFullName)); uploadRequest.Method = WebRequestMethods.Ftp.UploadFile; uploadRequest.Credentials = new NetworkCredential(username, password); uploadRequest.KeepAlive = false; //執行一個命令后關閉連接. uploadRequest.UseBinary = true; return uploadRequest.GetRequestStream(); } /// <summary> /// 获取文件路径 /// </summary> /// <param name="strPath"></param> /// <returns></returns> private string MapPath(string strPath) { if (HttpContext.Current != null) { return HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", "\\"); if (strPath.StartsWith("\\")) { strPath = strPath.TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } } #endregion