webapi批量上传照片(form-data)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | #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 |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步