码迷,mamicode.com
首页 > Web开发 > 详细

文件上传

时间:2015-03-19 00:51:42      阅读:251      评论:0      收藏:0      [点我收藏+]

标签:

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."
});
}
}
}
}

文件上传

标签:

原文地址:http://www.cnblogs.com/yishuangyan/p/4349159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!