Rest文件上传

文件上传时传过来一个stream

代码如下:

  /// <summary>
/// 上传文件
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="fileStream">文件流</param>
/// <returns></returns>
public ResponseType<int> UploadFile(string projectId, string DocId, string LastModifier, Stream fileStream)
{
ResponseType<int> result = new ResponseType<int>();
string Path = string.Empty;
try
{
if (fileStream == null)
{
throw new Exception("没有上传文件");
}
string relativePath = fileInfoBLL.GetFilePath(projectId, DocId);
Path = System.IO.Path.Combine(filePath, relativePath);
string fileName = fileInfoBLL.SaveFie(Path, fileStream); FilesInfo filesInfo = new FilesInfo();
filesInfo.DocManageId = Convert.ToInt32(DocId);
filesInfo.FileName = fileName;
filesInfo.FilePath = System.IO.Path.Combine(relativePath, fileName);
filesInfo.IsChecked = false;
filesInfo.LastmodifiedDateTime = DateTime.Now;
filesInfo.LastModifier = LastModifier;
filesInfo.ProjectId = Convert.ToInt32(projectId);
int fileId = fileInfoBLL.SaveFileInfo(filesInfo);
if (fileId > )
{
result.IsSuccess = true;
result.ErrorMessage = "文件保存成功!";
result.Value = fileId;
}
} catch (Exception ex)
{ ExceptionHandler.ExceptionHelper.Instance.HandleException(ex);
result.IsSuccess = false;
result.ErrorMessage = "文件保存失败!";
} return result;
}

黄色部分为真正文件上传代码:

    /// <summary>
/// 保存文件
/// </summary>
/// <param name="relatePath">文件保存的路径</param>
/// <param name="fileSteam">文件流</param>
public string SaveFie(string relatePath, Stream fileSteam)
{
string fileName = string.Empty;
try
{ if (!Directory.Exists(relatePath)) //判断文件目录
{
Directory.CreateDirectory(relatePath);
} using (var ms = new MemoryStream())
{
fileSteam.CopyTo(ms);
ms.Position = ; var encoding = Encoding.UTF8;
var reader = new StreamReader(ms, encoding);
var headerLength = 0L; //读取第一行
var firstLine = reader.ReadLine();
//计算偏移(字符串长度+回车换行2个字符)
headerLength += encoding.GetBytes(firstLine).LongLength + ; //读取第二行
var secondLine = reader.ReadLine();
//计算偏移(字符串长度+回车换行2个字符)
headerLength += encoding.GetBytes(secondLine).LongLength + ;
//解析文件名 fileName = new System.Text.RegularExpressions.Regex("filename=\"(?<fn>.*)\"").Match(secondLine).Groups["fn"].Value; //一直读到空行为止
while (true)
{
//读取一行
var line = reader.ReadLine();
//若到头,则直接返回
if (line == null ) break;
//若未到头,则计算偏移(字符串长度+回车换行2个字符)
headerLength += encoding.GetBytes(line).LongLength + ; if (string.IsNullOrEmpty(line))
break;
} //设置偏移,以开始读取文件内容
ms.Position = headerLength;
////减去末尾的字符串:“\r\n--\r\n”
ms.SetLength(ms.Length - encoding.GetBytes(firstLine).LongLength - * ); using (var fileToupload = new FileStream(System.IO.Path.Combine(relatePath,fileName), FileMode.Create))
{
ms.CopyTo(fileToupload);
fileToupload.Close();
fileToupload.Dispose();
}
}
}
catch (Exception ex)
{
ExceptionHandler.ExceptionHelper.Instance.HandleException(ex);
} return fileName;
}
上一篇:css的一些小技巧。修改input样式


下一篇:iOS开发之网络编程--获取文件的MIMEType