使用ASP上传多个文件.净MVC
本文关键字:文件 MVC ASP 使用 | 更新日期: 2023-09-27 18:02:56
我开发了一种方法,用于从表单接收文件,并在保存文件后从每个文件返回信息。可能有一个在互联网上做类似的,但我没有找到,但我仍在学习c#,我喜欢建立一些方法来帮助我。
我想发布它有两个建议,一个是检查我是否做得好,另一个原因是分享代码。
有什么建议吗?
如果你喜欢的话!使用它:)
我没有时间注释整个代码,抱歉!(
public String[,] upload(IEnumerable<HttpPostedFileBase> _files, List<string> _flSupportedTypes,int _flSizeLimit, string _serverPath)
{
/*
* Array Details
*
* { Fields detail }
* [1~] [0] - Status code
* [1] - Status message
* [2] - Upload file Name
* [3] - New file name
* [4] - Virtual Path
* [5] - Local Path
*
* { General details }
* [0] [0] - Status Code
* [1] - Status message
* [2] - total fields
* [3] - total fields processed
*/
int totalFieldsUpload = _files != null ? _files.Count() : 0;
int countFieldsUpload = 0;
int countFilesUpload = 0;
String[,] filesResult = new String[totalFieldsUpload + 1, 6];
if(totalFieldsUpload == 0)
{
filesResult[0, 0] = "0";
filesResult[0, 1] = "No fields";
filesResult[0, 2] = "0";
filesResult[0, 3] = "0";
}
else
{
filesResult[0, 0] = "1";
filesResult[0, 1] = "OK";
filesResult[0, 2] = totalFieldsUpload.ToString();
if (!Directory.Exists(_serverPath))
Directory.CreateDirectory(_serverPath);
foreach (var file in _files)
{
bool isContentOK = false;
countFieldsUpload++;
if (file != null)
{
String newfileName = DateTime.Now.ToFileTimeUtc() +
"_" + Path.GetRandomFileName() +
"." + file.FileName.ToString().Split('.').Last();
String localPath = _serverPath + newfileName;
String virtualPath = localPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"'", "/");
if (file.ContentLength <= _flSizeLimit)
{
foreach (var type in _flSupportedTypes)
{
if (file.ContentType == type)
{
file.SaveAs(localPath);
isContentOK = true;
countFilesUpload++;
break;
}
else
isContentOK = false;
}
filesResult[countFieldsUpload, 0] = "1";
filesResult[countFieldsUpload, 1] = isContentOK ? "OK" : "ContentType Failed";
filesResult[countFieldsUpload, 2] = file.FileName;
filesResult[countFieldsUpload, 3] = newfileName;
filesResult[countFieldsUpload, 4] = virtualPath;
filesResult[countFieldsUpload, 5] = localPath;
}
else
{
filesResult[countFieldsUpload, 0] = "0";
filesResult[countFieldsUpload, 1] = "Size Failed";
filesResult[countFieldsUpload, 2] = file.FileName;
}
}
else
{
filesResult[countFieldsUpload, 0] = "0";
filesResult[countFieldsUpload, 1] = "Field empty";
}
}
filesResult[0, 3] = countFilesUpload.ToString();
}
return filesResult;
}