UploadFileController

public class UploadFileController : Controller
{
#region 获取指定文件的已上传的文件块
/// <summary>
/// 获取指定文件的已上传的文件块
/// </summary>
/// <returns></returns>
public dynamic GetMaxChunk(string filePath)
{
string root = HttpContext.Current.Server.MapPath(filePath);
try
{
var md5 = Convert.ToString(HttpContext.Current.Request["md5"]);
var ext = Convert.ToString(HttpContext.Current.Request["ext"]);
int chunk = 0;

var fileName = md5 + "." + ext;

FileInfo file = new FileInfo(root + fileName);
if (file.Exists)
{
chunk = Int32.MaxValue;
}
else
{
if (Directory.Exists(root + "chunk\\" + md5))
{
DirectoryInfo dicInfo = new DirectoryInfo(root + "chunk\\" + md5);
var files = dicInfo.GetFiles();
chunk = files.Count();
if (chunk > 1)
{
chunk = chunk - 1; //当文件上传中时,页面刷新,上传中断,这时最后一个保存的块的大小可能会有异常,所以这里直接删除最后一个块文件
}
}
}
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = chunk
};
return data;
//return CommonResult.ToJsonStr(0, string.Empty, chunk);
}
catch
{
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = 0
};
return data;
}
}
#endregion

#region 上传文件
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileData"></param>
/// <returns></returns>
[HttpPost]
public dynamic Upload()
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string filePath = HttpContext.Current.Request.Form["filePath"];
string root = HttpContext.Current.Server.MapPath(filePath);
//如果进行了分片
if (HttpContext.Current.Request.Form.AllKeys.Any(m => m == "chunk"))
{
//取得chunk和chunks
int chunk = Convert.ToInt32(HttpContext.Current.Request.Form["chunk"]);//当前分片在上传分片中的顺序(从0开始)
int chunks = Convert.ToInt32(HttpContext.Current.Request.Form["chunks"]);//总分片数
//根据GUID创建用该GUID命名的临时文件夹
//string folder = Server.MapPath("~/UploadFiles/" + Request["md5"] + "/");
string folder = root + "chunk\\" + HttpContext.Current.Request["md5"] + "\\";
string path = folder + chunk;

//建立临时传输文件夹
if (!Directory.Exists(Path.GetDirectoryName(folder)))
{
Directory.CreateDirectory(folder);
}

FileStream addFile = null;
BinaryWriter AddWriter = null;
Stream stream = null;
BinaryReader TempReader = null;

try
{
//addFile = new FileStream(path, FileMode.Append, FileAccess.Write);
addFile = new FileStream(path, FileMode.Create, FileAccess.Write);
AddWriter = new BinaryWriter(addFile);
//获得上传的分片数据流
stream = file.InputStream;
TempReader = new BinaryReader(stream);
//将上传的分片追加到临时文件末尾
AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
}
finally
{
if (addFile != null)
{
addFile.Close();
addFile.Dispose();
}
if (AddWriter != null)
{
AddWriter.Close();
AddWriter.Dispose();
}
if (stream != null)
{
stream.Close();
stream.Dispose();
}
if (TempReader != null)
{
TempReader.Close();
TempReader.Dispose();
}
}
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = new { chunked = true, ext = Path.GetExtension(file.FileName) }
};
return data;
}
else//没有分片直接保存
{
string path = root + HttpContext.Current.Request["md5"] + Path.GetExtension(HttpContext.Current.Request.Files[0].FileName);
if (!Directory.Exists(Path.GetDirectoryName(root)))
{
Directory.CreateDirectory(root);
}
HttpContext.Current.Request.Files[0].SaveAs(path);
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = new { chunked = false }
};
return data;
}
}
#endregion

#region 合并文件
/// <summary>
/// 合并文件
/// </summary>
/// <returns></returns>
[HttpPost]
public dynamic MergeFiles(dynamic obj)
{

string filePath = obj.filePath;// HttpContext.Current.Request["filePath"];
string root = HttpContext.Current.Server.MapPath(filePath);

string guid = obj.md5;// HttpContext.Current.Request["md5"];
string ext = obj.ext;// HttpContext.Current.Request["ext"];
string sourcePath = Path.Combine(root, "chunk\\" + guid + "\\");//源数据文件夹
string targetPath = Path.Combine(root, guid + ext);//合并后的文件

DirectoryInfo dicInfo = new DirectoryInfo(sourcePath);
if (Directory.Exists(Path.GetDirectoryName(sourcePath)))
{
FileInfo[] files = dicInfo.GetFiles();
foreach (FileInfo file in files.OrderBy(f => int.Parse(f.Name)))
{
FileStream addFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write);
BinaryWriter AddWriter = new BinaryWriter(addFile);

//获得上传的分片数据流
Stream stream = file.Open(FileMode.Open);
BinaryReader TempReader = new BinaryReader(stream);
//将上传的分片追加到临时文件末尾
AddWriter.Write(TempReader.ReadBytes((int)stream.Length));
//关闭BinaryReader文件阅读器
TempReader.Close();
stream.Close();
AddWriter.Close();
addFile.Close();

TempReader.Dispose();
stream.Dispose();
AddWriter.Dispose();
addFile.Dispose();
}
DeleteFolder(sourcePath);
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = new { chunked = true, hasError = false, savePath = System.Web.HttpUtility.UrlEncode(targetPath) }
};
return data;
}
else
{
var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = new { hasError = true }
};
return data;
}
}
#endregion

#region 删除文件夹及其内容
/// <summary>
/// 删除文件夹及其内容
/// </summary>
/// <param name="dir"></param>
private void DeleteFolder(string strPath)
{
//删除这个目录下的所有子目录
if (Directory.GetDirectories(strPath).Length > 0)
{
foreach (string fl in Directory.GetDirectories(strPath))
{
Directory.Delete(fl, true);
}
}
//删除这个目录下的所有文件
if (Directory.GetFiles(strPath).Length > 0)
{
foreach (string f in Directory.GetFiles(strPath))
{
System.IO.File.Delete(f);
}
}
Directory.Delete(strPath, true);
}
#endregion

#region 更新用户上传记录
/// <summary>
/// 更新用户上传记录
/// </summary>
/// <returns></returns>
[HttpPost]
public dynamic AddUploadRecord()
{

var data = new UploadFileModelMsg()
{
code = 0,
errMsg = "",
data = new { }
};
return data;
}
#endregion

#region 下载

[HttpGet]
public dynamic DownloadFile(string url)
{
var browser = String.Empty;
if (HttpContext.Current.Request.UserAgent != null)
{
browser = HttpContext.Current.Request.UserAgent.ToUpper();
}
string filePath = HttpContext.Current.Server.MapPath(url);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
FileStream fileStream = File.OpenRead(filePath);
httpResponseMessage.Content = new StreamContent(fileStream);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName =
browser.Contains("FIREFOX")
? Path.GetFileName(filePath)
: HttpUtility.UrlEncode(Path.GetFileName(filePath))
//FileName = HttpUtility.UrlEncode(Path.GetFileName(filePath))
};

return ResponseMessage(httpResponseMessage);
}

#endregion

#region 上传, 删除文件
//上传文件的目录
private static readonly string subDicName = "Uploads";

/// <summary>
/// 上传文件(IMES,layui的上传用的老版本的有跨域问题,远程下载2.0版的拿不过)
/// </summary>
/// <returns></returns>
[HttpPost]
public ApiReuslt<string> UploadFile()
{

if (HttpContext.Current.Request.Files.Count > 0)
{
try
{
var file = HttpContext.Current.Request.Files[0];
string fileDir = HttpContext.Current.Server.MapPath(subDicName);
string saveFilePath = Path.Combine(subDicName, file.FileName);//文件保存的路径
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
try
{
file.SaveAs(fileDir + file.FileName);
return ApiReuslt<string>.Success(saveFilePath);
}
catch (Exception e)
{
throw new ApplicationException(e.Message);
}

}
catch (Exception ex)
{
return ApiReuslt<string>.Failed("上传失败,请联系管理员");
}
}
return ApiReuslt<string>.Failed("不存在文件流");
}

///// <summary>
///// 删除文件
///// </summary>
///// <param name="virtualFilePath"></param>
///// <returns>bool是否成功</returns>
[HttpPost]
public ApiReuslt<bool> DeleteFile(string virtualFilePath)
{

if (string.IsNullOrEmpty(virtualFilePath))
{
return ApiReuslt<bool>.Failed(nameof(virtualFilePath) + "参数为空");
}
var fileFullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, virtualFilePath);
if (File.Exists(fileFullPath))
{
File.Delete(fileFullPath);
return ApiReuslt<bool>.Success(true);
}
else
{
return ApiReuslt<bool>.Success(1, 0, true, "文件不存在");//文件不存在当作删除成功
}

}


/// <summary>
/// MVC后台代理中转上传
/// </summary>
/// <returns></returns>
public async Task<ApiReuslt<FileInfoModel>> UploadFiles()
{
string fileDownUrl = string.Empty;
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var item in provider.Contents)
{

if (item.Headers.ContentDisposition.FileName == null) continue;
var ms = item.ReadAsStreamAsync().Result;
using (var br = new BinaryReader(ms))
{
if (ms.Length <= 0)
break;
var data = br.ReadBytes((int)ms.Length);
var info = new FileInfo(item.Headers.ContentDisposition.FileName.Replace("\"", ""));
string fileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, subDicName);//文件保存的路径
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
string tempFileName = $"{ DateTime.Now.ToString("yyyyMMddHHmmssff")}_{info.Name}";//重命名之后的的文件名
string fileFullPath = Path.Combine(fileDir, tempFileName); //保存的位置,防上同名文件覆盖之前上传的文件
File.WriteAllBytes(fileFullPath, data);
fileDownUrl = subDicName + "/" + tempFileName;
FileInfoModel fileInfoModel = new FileInfoModel()
{
Name = System.IO.Path.GetFileNameWithoutExtension(fileFullPath),//不要扩展名
Size = (int)info.Length,
Extension = info.Extension,
VirtualFilePath = fileDownUrl,
FullFilePath = fileFullPath
};
return ApiReuslt<FileInfoModel>.Success(fileInfoModel);
}
}

}
catch (Exception ex)
{
return ApiReuslt<FileInfoModel>.Failed(default(FileInfoModel), ex.Message);
}
return ApiReuslt<FileInfoModel>.Success(default(FileInfoModel));
}
#endregion
}

posted @ 2018-11-27 09:46  爱尚~为技术疯狂  阅读(317)  评论(0编辑  收藏  举报