ASP.NET MVC我的博客项目中的照片上载问题



当我上传照片时,页面只是刷新,而不是在ASP.NET MVC我的博客项目中上传照片。我在Stack OverFlow中查找了解决方案,但我没有处理这个问题。我不知道该在这里写哪些代码,因为我第一次尝试用ASP.NET创建博客网站。如果你问我什么代码,我会很快在这里发布。感谢合作。

例如,假设您的型号是

public class blog
{
public int Id { get; set; }
public string Code { get; set; }
public string Photo1 { get; set; }
}

在这里,我将照片存储在服务器中(不在数据库中(控制器

public ActionResult BeginUploadPhoto(int Id)
{
var Blog= db.blog.Where(a => a.Id == Id).FirstOrDefault();
return View(Blog);
}
public ActionResult UploadPhoto(int? Id, HttpPostedFileBase Logo)
{
BlogCP = db.Blog.Find(Id);
WebImage img = new WebImage(Logo.InputStream);
if (img.Width > 500)
img.Resize(500, 500);
// to reduce the size upon upload
string extension = Path.GetExtension(Logo.FileName);
// get your photo extenstion
string filename = Guid.NewGuid().ToString();
// rename the upload photo
var path = Path.Combine(Server.MapPath("~/BlogPhoto/"), filename + extension);
// make sure that you create a folder BlogPhoto in your project or you can 
//name it anything you like
string savepath = "~/BlogPhoto/" + filename + extension;
BlogCP.Photo1= savepath;

img.Save(path);
// save photo in your server
if (ModelState.IsValid)
{

db.Entry(BlogCP ).Property(r => r.Photo1).IsModified = true;
db.SaveChanges();
return RedirectToAction("Index","Staff");
}

return RedirectToAction("Index");
}

查看

@model ProjectName.Entities.Blog
@{
ViewBag.Title = "BeginUploadPhoto";
}
<div class="container">

@if (Model.Photo1 != null)
{
<img id="Preview" class="img-thumbnail" src=@Model.Photo1/>
}
@using (Html.BeginForm("UploadPhoto", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
{
@Html.HiddenFor(m => m.Id)
<div>
<a>Select and upload Photo</a>
<input type="file" id="Logo" name="Logo" 
<input type="file" id="Logo" name="Logo" accept="image/*" onchange="loadFile(event)">
</div>
<div class="form-group">
<button id="btnUpload"
class="btn btn-sm btn-primary"
formnovalidate="formnovalidate"
data-pdsa-action="upload">
<i class="glyphicon glyphicon-upload"></i>
&nbsp;Upload
</button>
</div>
}
}

最新更新