为用户创建一个头像上传表单 [英] Create an avatar upload form for users
问题描述
我使用ASP.Net MVC 5,我要创建我的用户配置文件的化身。我不知道我在做什么,到目前为止是正确的方式,尤其是出于安全原因,所以我希望得到一些建议。
I'm using ASP.Net MVC 5 and I want to create an avatar for my user profiles. I'm not sure if what I'm doing so far is the right way, especially for security reasons so I wanted to get some advice.
在View:
@using (Html.BeginForm("ManageUser", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="Add Avatar" />
}
在控制器:
internal static bool SaveAvatar(User user, HttpPostedFileBase file)
{
if (file == null || file.ContentLength <= 0 || file.ContentLength > MAX_LENGTH)
return false;
//I think I should convert the file somehow instead of saving it
var path = HostingEnvironment.MapPath("~/img/avatar/") + string.Format("{0}.png", user.UserName);
file.SaveAs(path);
user.HasAvatar = true;
return true;
}
我有几个担心:
- 在上面的code,因为我评论,我觉得只是储蓄,而不是
哪些用户已派出我,我应该以某种方式使用库转换
图像以PNG文件,并保存它。如果是这样,有一个很好的和简单的图书馆这样做呢? - 我不知道是否使用用户名作为文件将是不错的主意。毕竟,他们选择这个名称,它是不是我决定的。
- 的是它使用普通的图像是一个好主意或者我应该创建一个控制器来验证请求或击溃请求到的隐藏的形象?
- In the code above, as I commented, I think instead of just saving what user has sent to me, I should somehow use a library to convert the image to a PNG file and save it. If so, is there a good and simple library to do this?
- I wonder whether using the user's name as a file would be good idea. After all, they choose this name and it is not something I decide.
- Is it a good idea to use plain images or should I create a controller to validate requests or rout the requests to a hidden image?
如果我在做什么的 TOTALLY 错了,你知道更好的源来学习的正确方法,请点我在正确的方向。谢谢你。
If what I'm doing is TOTALLY wrong and you know a better source to learn the right way, please point me in the right direction. Thanks.
推荐答案
您可以使用这个类上传文件到服务器:
you can use this class for Upload a file to server :
public static class FileUpload
{
public static char DirSeparator = System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = HttpContext.Current.Server.MapPath("~\\Content" + DirSeparator + "Uploads" + DirSeparator);
public static string UploadFile(HttpPostedFileBase file)
{
// Check if we have a file
if (null == file) return "";
// Make sure the file has content
if (!(file.ContentLength > 0)) return "";
string fileName =DateTime.Now.Millisecond+ file.FileName;
string fileExt = Path.GetExtension(file.FileName);
// Make sure we were able to determine a proper extension
if (null == fileExt) return "";
// Check if the directory we are saving to exists
if (!Directory.Exists(FilesPath))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(FilesPath);
}
// Set our full path for saving
string path = FilesPath + DirSeparator + fileName;
// Save our file
file.SaveAs(Path.GetFullPath(path));
// Save our thumbnail as well
ResizeImage(file, 70, 70);
// Return the filename
return fileName;
}
public static void DeleteFile(string fileName)
{
// Don't do anything if there is no name
if (fileName.Length == 0) return;
// Set our full path for deleting
string path = FilesPath + DirSeparator + fileName;
string thumbPath = FilesPath + DirSeparator + "Thumbnails" + DirSeparator + fileName;
RemoveFile(path);
RemoveFile(thumbPath);
}
private static void RemoveFile(string path)
{
// Check if our file exists
if (File.Exists(Path.GetFullPath(path)))
{
// Delete our file
File.Delete(Path.GetFullPath(path));
}
}
public static void ResizeImage(HttpPostedFileBase file, int width, int height)
{
string thumbnailDirectory = String.Format(@"{0}{1}{2}", FilesPath, DirSeparator, "Thumbnails");
// Check if the directory we are saving to exists
if (!Directory.Exists(thumbnailDirectory))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(thumbnailDirectory);
}
// Final path we will save our thumbnail
string imagePath = String.Format(@"{0}{1}{2}", thumbnailDirectory, DirSeparator, file.FileName);
// Create a stream to save the file to when we're done resizing
FileStream stream = new FileStream(Path.GetFullPath(imagePath), FileMode.OpenOrCreate);
// Convert our uploaded file to an image
Image OrigImage = Image.FromStream(file.InputStream);
// Create a new bitmap with the size of our thumbnail
Bitmap TempBitmap = new Bitmap(width, height);
// Create a new image that contains are quality information
Graphics NewImage = Graphics.FromImage(TempBitmap);
NewImage.CompositingQuality = CompositingQuality.HighQuality;
NewImage.SmoothingMode = SmoothingMode.HighQuality;
NewImage.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Create a rectangle and draw the image
Rectangle imageRectangle = new Rectangle(0, 0, width, height);
NewImage.DrawImage(OrigImage, imageRectangle);
// Save the final file
TempBitmap.Save(stream, OrigImage.RawFormat);
// Clean up the resources
NewImage.Dispose();
TempBitmap.Dispose();
OrigImage.Dispose();
stream.Close();
stream.Dispose();
}
}
您还可以保存他们的照片使用 ResizeImage
方法的缩略图,并在控制器,我会在数据库中这种方式保存的文件名:
you can also save the thumbnail of their photos using ResizeImage
method and In the controller I'll save file name in the database this way:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(User user, HttpPostedFileBase file)
{
// TODO: Add insert logic here
user.Pictuer = FileUpload.UploadFile(file);
db.User.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
也为转换上传的图片,您可以使用在 UploadFile这个code
方法:
also for convert uploaded images you can use this code inside UploadFile
method :
System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"C:\test.bmp");
// Save the image in JPEG format.
image1.Save(@"C:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
// Save the image in GIF format.
image1.Save(@"C:\test.gif", System.Drawing.Imaging.ImageFormat.Gif);
// Save the image in PNG format.
image1.Save(@"C:\test.png", System.Drawing.Imaging.ImageFormat.Png);
这篇关于为用户创建一个头像上传表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!