文件上传
public class FileUploadController : DnnApiController
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof (FileUploadController));
private readonly IFileManager _fileManager = FileManager.Instance;
private readonly IFolderManager _folderManager = FolderManager.Instance;
[DnnAuthorize]
[HttpPost]
[IFrameSupportedValidateAntiForgeryToken]
public HttpResponseMessage UploadFile()
{
var statuses = new List<FilesStatus>();
try
{
//todo can we eliminate the HttpContext here
UploadWholeFile(HttpContextSource.Current, statuses);
}
catch (Exception exc)
{
Logger.Error(exc);
}
return IframeSafeJson(statuses);
}
private HttpResponseMessage IframeSafeJson(List<FilesStatus> statuses)
{
//return json but label it as plain text
return new HttpResponseMessage
{
Content = new StringContent(JsonConvert.SerializeObject(statuses))
};
}
private static bool IsAllowedExtension(string fileName)
{
var extension = Path.GetExtension(fileName);
//regex matches a dot followed by 1 or more chars followed by a semi-colon
//regex is meant to block files like "foo.asp;.png" which can take advantage
//of a vulnerability in IIS6 which treasts such files as .asp, not .png
return !string.IsNullOrEmpty(extension)
&& Host.AllowedExtensionWhitelist.IsAllowedExtension(extension)
&& !Regex.IsMatch(fileName, @"\..+;");
}
// Upload entire file
private void UploadWholeFile(HttpContextBase context, ICollection<FilesStatus> statuses)
{
for (var i = 0; i < context.Request.Files.Count; i++)
{
var file = context.Request.Files[i];
if (file == null) continue;
var fileName = Path.GetFileName(file.FileName);
if (IsAllowedExtension(fileName))
{
var userFolder = _folderManager.GetUserFolder(UserInfo);
//todo: deal with the case where the exact file name already exists.
var fileInfo = _fileManager.AddFile(userFolder, fileName, file.InputStream, true);
var fileIcon = Entities.Icons.IconController.IconURL("Ext" + fileInfo.Extension, "32x32");
if (!File.Exists(context.Server.MapPath(fileIcon)))
{
fileIcon = Entities.Icons.IconController.IconURL("File", "32x32");
}
statuses.Add(new FilesStatus
{
success = true,
name = fileName,
extension = fileInfo.Extension,
type = fileInfo.ContentType,
size = file.ContentLength,
progress = "1.0",
url = FileManager.Instance.GetUrl(fileInfo),
thumbnail_url = fileIcon,
message = "success",
id = fileInfo.FileId,
});
}
else
{
statuses.Add(new FilesStatus
{
success = false,
name = fileName,
message = "File type not allowed."
});
}
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。