上传图片,但没有看到图像 [英] Uploading image, but doesnt see the image
问题描述
大家好,
我可以上传和拍照。但是它没有显示图像。
这是我上传的图片:
[HttpPost]
public ActionResult EditPhotos(ImageUploadModel ImageUpload)
{
如果跨度>(ModelState.IsValid)
{
<跨度类= 代码关键字> VAR 跨度> DirSeparator = Path.DirectorySeparatorChar;
var fileName = Path.GetFileName(ImageUpload.file.FileName);
var path = Server.MapPath( @ \\Images\\profile + DirSeparator + fileName.Replace(' +',' _'));
ImageUpload.file.SaveAs(path);
ViewBag.Message = 文件已成功上传;
// ModelState.Clear();
string username = User.Identity.Name;
// 获取userprofile
UserProfile user = db.userProfiles.FirstOrDefault( u = > u.UserName.Equals(username));
// 更新字段
byte [] uploadedFile = new byte [ImageUpload。 file.ContentLength];
ImageUpload.file.InputStream.Read(uploadedFile, 0 ,ImageUpload.file.ContentLength);
user.file = uploadedFile;
user.ImageMimeType = ImageUpload.file.ContentType;
db.Entry(user).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach ( var eve in e.EntityValidationErrors)
{
Console.WriteLine ( 状态\{1} \中类型为\{0} \的实体具有以下验证错误:,
eve.Entry.Entity.GetType()。Name,eve.Entry.State);
foreach ( var ve in eve.ValidationErrors)
{
Console.WriteLine( - Property:\{ 0} \,错误:\{1} \,
ve.PropertyName,ve.ErrorMessage);
}
}
throw ;
}
}
// return View ();
return RedirectToAction( 编辑,routeValues: new {controller = Account,activetab = tabs-2}) ;
}
和这用于获取图像:
public ActionResult GetImage ( int id)
{
var stream =(< span class =code-sdkkeyword> from m in db.userProfiles where m。 Id == id select m.file).FirstOrDefault();
// byte [] image = db.userProfiles.Where(p => p.Id == id).Select(img => img.file).FirstOrDefault();
// var stream = new MemoryStream(image.ToArray());
return 文件(stream, image / png);
}
这个视图:
< div class = 表格响应 >
< table class = table >
< tr>
< th>< img width = 200 height = 150 src = @ Url.Action( GetImage ,帐户 ,new {id = Model.Id}) > < / th >
< / tr >
< / table >
< / div >
所以我可以上传图像并保存图像。但它上传后不显示图像。我在Chrome中点了f12,我看到路径是:src =/ Account / GetImage / 58。什么是不正确的。但是如何改变呢?
谢谢
使用下面的代码并根据你的需要更改路径要求。
1.查看
@using(Html.BeginForm(UploadExcel,UserDetails ,FormMethod.Post,new {enctype =multipart / form-data}))//(方法名称,控制器名称,帖子,类型)
{
@ Html.ValidationSummary(true)
@ Html.LabelFor(model => model.Files)
< input type =filename =fileuploadmultiple =multiplerequired =required/>
@ Html.ValidationMessageFor(model => model.Files )
< input type =submitvalue =Create/>
} < br $>
2.控制器
[HttpPost]
公共ActionResult UploadExcel(HttpPostedFileBase [] fileupload)
{
HttpPostedFileBase file = fileupload;
if(file == null)
{
ModelState.AddModelError(File,Please Upload your file);
}
else if(file.ContentLength> 0)
{
int MaxContentLength = 1024 * 1024 * 3; // 3 MB
string [] AllowedFileExtensions = new string [] {.jpg,。gif,。png,。pdf};
如果(!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf( ''))))
{
ViewBag.Message =文件,请提供以下类型的文件:+ string.Join(,,AllowedFileExtensions);
}
else if(file.ContentLength> MaxContentLength)
{
ViewBag.Message =文件,您的文件太大,允许的最大尺寸为:+ MaxContentLength +MB;
}
else
{
// TO:DO
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(〜 / Content / Upload),fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message =文件上传成功;
}
}
返回查看();
}
HI,
谢谢你的answare。但是你需要编码才能在上传后看到图像。
我有这样的观点:
< div id = tabs-2 >
@using(Html.BeginForm( EditPhotos, 帐户, new {id = form,enctype = multipart / form-data}))
{
@ Html.AntiForgeryToken()
< div class = form-horizontal >
< h4>照片< / h4 >
< hr /> ;
@ Html.HiddenFor(model = > model.Id)
< div class = lifile >
< div id = 上传选项 >
< div class = editor-label >
@ Html.ValidationMessageFor(model = > model.file)
@ Html.ValidationSummary( true )
< / div >
< / div >
< / div >
< br />
< div class = 表格响应 >
< table class = < span class =code-string> table >
< tr>
@ *< th> < / th > * @
< th>< img width = 200 height = 150 src = @ Url.Action( account = ,new {id = Model.Id}) /> < / th >
< / tr >
< ; / 表 >
< / div >
< input type = file name = 文件 class = filestyle data-buttontext = 查找文件 >
< br />
< div class = 进度进度-striped >
< div class = progress-bar progress-bar-success> 0%< / div >
< / div >
< div id = status > < / div >
< br />
@ * @ Html.ActionLink( 上传照片, 上传)* @
< div class = pull-left >
< div 类 = col-md-offset-0 >
< input type = submit value = 保存 accept = image / x-png,image / gif,image / jpeg class = btn btn-default pull-left />
< / div >
< / div >
< / div >
}
< br />< br />
< div>
@ Html.ActionLink( 返回列表, 索引)
< / div >
< / div >
和方法,如下所示:
[HttpPost]
public ActionResult EditPhotos(ImageUploadModel ImageUpload)
{
if (ImageUpload.file == null || ImageUpload.file.ContentLength == 0 )
{
ModelState.AddModelError(file, 此字段为 );
}
if (ModelState.IsValid)
{
var DirSeparator = Path.DirectorySeparatorChar;
var fileName = Path.GetFileName(ImageUpload.file.FileName);
var path = Path.Combine(Server.MapPath( @ < span class =code-string> \\Images\\profile + @ \ + fileName.Replace(' +',' _')));
ImageUpload.file.SaveAs(path);
ViewBag.Path = String .Format( / Images / profile / {0},fileName);
ViewBag.Message = 文件已成功上传;
// ModelState.Clear();
string username = User.Identity.Name;
// 获取userprofile
UserProfile user = db.userProfiles.FirstOrDefault( u = > u.UserName.Equals(username));
// 更新字段
byte [] uploadedFile = new byte [ImageUpload。 file.ContentLength];
ImageUpload.file.InputStream.Read(uploadedFile, 0 ,ImageUpload.file.ContentLength);
user.file = uploadedFile;
user.ImageMimeType = ImageUpload.file.ContentType;
db.Entry(user).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach ( var eve in e.EntityValidationErrors)
{
Console.WriteLine ( 状态\{1} \中类型为\{0} \的实体具有以下验证错误:,
eve.Entry.Entity.GetType()。Name,eve.Entry.State);
foreach ( var ve in eve.ValidationErrors)
{
Console.WriteLine( - Property:\{ 0} \,错误:\{1} \,
ve.PropertyName,ve.ErrorMessage);
}
}
throw ;
}
}
// return View ();
return RedirectToAction( 编辑,routeValues: new {controller = < span class =code-string> Account,activetab = tabs-2});
}
但仍未显示图片
现在输出如下:
< img width = 200 height = 150 src = / Account /%40ViewBag.path / 58 >
但这必须是路径:
G:\Mijn Documents\My网络Sites\Lolabikes - Copy\C#\ContosoUniversity\Images\profile\6a00d8341c562c53ef0148c82ff5d1970c-800wi.jpg
HI everybody,
I can upload and image. But it doesnt show the image.
this I have for uploading image:
[HttpPost]
public ActionResult EditPhotos(ImageUploadModel ImageUpload)
{
if (ModelState.IsValid)
{
var DirSeparator = Path.DirectorySeparatorChar;
var fileName = Path.GetFileName(ImageUpload.file.FileName);
var path = Server.MapPath("@\\Images\\profile" + DirSeparator + fileName.Replace('+', '_'));
ImageUpload.file.SaveAs(path);
ViewBag.Message = "File has been uploaded successfully";
//ModelState.Clear();
string username = User.Identity.Name;
// Get the userprofile
UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
// Update fields
byte[] uploadedFile = new byte[ImageUpload.file.ContentLength];
ImageUpload.file.InputStream.Read(uploadedFile, 0, ImageUpload.file.ContentLength);
user.file = uploadedFile;
user.ImageMimeType = ImageUpload.file.ContentType;
db.Entry(user).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
//return View();
return RedirectToAction("Edit", routeValues: new { controller = "Account", activetab = "tabs-2" });
}
and this for getting the image:
public ActionResult GetImage(int id)
{
var stream = (from m in db.userProfiles where m.Id == id select m.file).FirstOrDefault();
// byte[] image = db.userProfiles.Where(p => p.Id == id).Select(img => img.file).FirstOrDefault();
//var stream = new MemoryStream(image.ToArray());
return File(stream, "image/png");
}
and this for the view:
<div class="table-responsive">
<table class="table">
<tr>
<th><img width="200" height="150" src="@Url.Action("GetImage", "Account", new { id = Model.Id })"></th>
</tr>
</table>
</div>
So I can upload the image and it is saving the image. But it doesnt show the image after uploading. I dit f12 in Chrome, and I see that the path is: src="/Account/GetImage/58" . What ofcourse is not correct. But how to change that?
Thank you
Use below code and change path as per your requirements.
1. View
@using (Html.BeginForm("UploadExcel", "UserDetails", FormMethod.Post, new { enctype = "multipart/form-data" })) // ("Method name", "Controller name",post, type)
{
@Html.ValidationSummary(true)
@Html.LabelFor(model => model.Files)
<input type="file" name="fileupload" multiple="multiple" required="required"/>
@Html.ValidationMessageFor(model => model.Files)
<input type="submit" value="Create" />
}
2. Controller
[HttpPost]
public ActionResult UploadExcel(HttpPostedFileBase[] fileupload)
{
HttpPostedFileBase file = fileupload;
if (file == null)
{
ModelState.AddModelError("File", "Please Upload Your file");
}
else if (file.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 3; //3 MB
string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".pdf" };
if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ViewBag.Message = "File, Please file of type: " + string.Join(", ", AllowedFileExtensions);
}
else if (file.ContentLength > MaxContentLength)
{
ViewBag.Message = "File, Your file is too large, maximum allowed size is: " + MaxContentLength + " MB";
}
else
{
//TO:DO
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Upload"), fileName);
file.SaveAs(path);
ModelState.Clear();
ViewBag.Message = "File uploaded successfully";
}
}
return View();
}
HI,
thank you for your answare. But where you have to code for seeing the image after uploading.
I have the view like this:
<div id="tabs-2"> @using (Html.BeginForm("EditPhotos", "Account", new { id = "form", enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-horizontal"> <h4>Photos</h4> <hr /> @Html.HiddenFor(model => model.Id) <div class="lifile"> <div id="upload-choices"> <div class="editor-label"> @Html.ValidationMessageFor(model => model.file) @Html.ValidationSummary(true) </div> </div> </div> <br /> <div class="table-responsive"> <table class="table"> <tr> @*<th></th>*@ <th><img width="200" height="150" src="@Url.Action(" account=", new { id = Model.Id})" /></th> </tr> </table> </div> <input type="file" name="File" class="filestyle" data-buttontext="Find file"> <br /> <div class="progress progress-striped"> <div class="progress-bar progress-bar-success">0%</div> </div> <div id="status"></div> <br /> @*@Html.ActionLink("Upload photos", "Upload")*@ <div class="pull-left"> <div class="col-md-offset-0"> <input type="submit" value="Save" accept="image/x-png, image/gif, image/jpeg" class="btn btn-default pull-left" /> </div> </div> </div> } <br /><br /> <div> @Html.ActionLink("Back to List", "Index") </div> </div>
and the method, like this:
[HttpPost] public ActionResult EditPhotos(ImageUploadModel ImageUpload) { if (ImageUpload.file == null || ImageUpload.file.ContentLength == 0) { ModelState.AddModelError("file", "This field is requird"); } if (ModelState.IsValid) { var DirSeparator = Path.DirectorySeparatorChar; var fileName = Path.GetFileName(ImageUpload.file.FileName); var path = Path.Combine(Server.MapPath(@"\\Images\\profile" + @"\" + fileName.Replace('+', '_'))); ImageUpload.file.SaveAs(path); ViewBag.Path = String.Format("/Images/profile/{0}", fileName); ViewBag.Message = "File has been uploaded successfully"; //ModelState.Clear(); string username = User.Identity.Name; // Get the userprofile UserProfile user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username)); // Update fields byte[] uploadedFile = new byte[ImageUpload.file.ContentLength]; ImageUpload.file.InputStream.Read(uploadedFile, 0, ImageUpload.file.ContentLength); user.file = uploadedFile; user.ImageMimeType = ImageUpload.file.ContentType; db.Entry(user).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } } //return View(); return RedirectToAction("Edit", routeValues: new { controller = "Account", activetab = "tabs-2" }); }
but still not showing the image
Now the output is like this:
<img width="200" height="150" src="/Account/%40ViewBag.path/58">
But this has to be the path:
G:\Mijn Documents\My Web Sites\Lolabikes - Copy\C#\ContosoUniversity\Images\profile\6a00d8341c562c53ef0148c82ff5d1970c-800wi.jpg
这篇关于上传图片,但没有看到图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!