/// <summary> /// 将自身作为multipart/form-data的一个文件项 /// </summary> /// <param name="stream">数据流</param> /// <param name="fileName">文件友好名称</param> /// <exception cref="ArgumentNullException"></exception> public MulitpartFile(Stream stream, string fileName) { if (stream == null) { throw new ArgumentNullException("stream"); } this.stream = stream; this.FileName = fileName; this.ContentType = MimeTable.GetContentType(fileName); }
/// <summary> /// multipart/form-data的一个文件项 /// </summary> /// <param name="localFilePath">本地文件路径</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="FileNotFoundException"></exception> public MulitpartFile(string localFilePath) { if (string.IsNullOrEmpty(localFilePath)) { throw new ArgumentNullException(); } if (File.Exists(localFilePath) == false) { throw new FileNotFoundException(localFilePath); } this.filePath = localFilePath; this.FileName = Path.GetFileName(localFilePath); this.ContentType = MimeTable.GetContentType(localFilePath); }
/// <summary> /// 文件扩展名与文件类型/子类型映射 /// </summary> static MimeTable() { var datas = from line in MimeTable.LoadMimeLines() let kv = line.Split(new[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries) let ext = kv.FirstOrDefault() let contenType = kv.LastOrDefault() select new { ext, contenType }; foreach (var item in datas) { if (mimeTable.ContainsKey(item.ext) == false) { mimeTable.Add(item.ext, item.contenType); } } }
/// <summary> /// 文件内容 /// </summary> /// <param name="stream">文件流</param> /// <param name="name">名称</param> /// <param name="fileName">文件名</param> /// <param name="contentType">文件Mime</param> public MulitpartFileContent(Stream stream, string name, string fileName, string contentType) : base(stream) { if (this.Headers.ContentDisposition == null) { var disposition = new ContentDispositionHeaderValue("form-data"); disposition.Name = string.Format("\"{0}\"", name); disposition.FileName = string.Format("\"{0}\"", fileName); this.Headers.ContentDisposition = disposition; } if (string.IsNullOrEmpty(contentType)) { contentType = MimeTable.GetContentType(fileName); } this.Headers.ContentType = new MediaTypeHeaderValue(contentType); }