如何获取数据库图像并在ASP.NET MVC 4中显示另一个页面 [英] How to get database images and display another page in ASP.NET MVC 4
问题描述
查看页面
=========
View Page
=========
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="../../Scripts/form.js" type="text/javascript"></script>
<script>
$(document).on("click", "#btnid", function (event) {
event.preventDefault();
var fileOptions = {
success: res,
dataType: "json"
}
$("#formid").ajaxSubmit(fileOptions);
});
</script>
<script src="//code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ShowImagePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#<%=ImgPrv.ClientID%>').prop('src', e.target.result)
.width(240)
.height(150);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<div id="dialog">
@Html.ValidationMessage("DuplicateGroup")
@Html.ValidationMessage("GroupSaved")
</div>
@using (Html.BeginForm("SubmitImage", "Carrer", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<div class="float-left">
<div id="dialog">
@Html.ValidationMessage("DuplicateImage")
@Html.ValidationMessage("ImageSaved")
</div>
<center>
<h2>Submit Image</h2>
</center>
<div class="editor-label">
@Html.LabelFor(Model => Model.strGroupId)
</div>
<div class="editor-field">
@Html.EditorFor(Model => Model.strGroupId)
<div id="dialog">
@Html.ValidationMessageFor(Model => Model.strGroupId)
</div>
</div>
<div class="editor-label">
@Html.LabelFor(Model => Model.strGroupName)
</div>
<div class="editor-field">
@Html.EditorFor(Model => Model.strGroupName)
<div id="dialog">
@Html.ValidationMessageFor(Model => Model.strGroupName)
</div>
</div>
<div class="editor-label">
@Html.LabelFor(Model => Model.SelectImage)
</div>
<input type="file" name="file" id="file" />
<div id="dialog">
@Html.ValidationMessage("CustomError")
</div>
<center>
<input type="submit" value="Upload" />
</center>
</div>
</fieldset>
}
@Scripts.Render("~/bundles/jqueryval")
控制器代码
====================
Controller code
====================
public class CarrerController : Controller
{
//
// GET: /Carrer/
public ActionResult SubmitImage()
{
return View();
}
[HttpPost]
//public ActionResult SubmitImage(HttpPostedFileBase file, Carrer model)
public ActionResult SubmitImage(Carrer model)
{
//string blnImageUploaded;
if (model.file != null && model.file.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/UploadImages"),
Path.GetFileName(model.file.FileName));
model.file.SaveAs(path);
InsertMapDetails(model, path);
//if (blnImageUploaded == true)
//{
ViewBag.Message = "File uploaded successfully";
//}
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View();
}
public ActionResult Save(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
}
return View();
}
public bool checkImageUploated(string strGroupId, string strGroupName, string strFullPath) //This method checks the valid image is uploaded in table or not.
{
bool blnValidImage = false;
string connString = ConfigurationManager.ConnectionStrings["DBconnectionString"].ConnectionString; // Read the connection string from the web.config file
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Update MAP set IMAGEPATH = '" + strFullPath + "' where GROUPID = '" + strGroupId + "' and GROUPNAME = '" + strGroupName + "' ", conn);
blnValidImage = Convert.ToBoolean(cmd.ExecuteNonQuery());
return blnValidImage;
}
}
public string InsertMapDetails(Carrer model, string strFullPath)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBconnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into MAP (GROUPID,GROUPNAME,IMAGEPATH) values('" + model.strGroupId.Trim() + "','" + model.strGroupName.Trim() + "','" + strFullPath + "')";
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}
catch (Exception es)
{
throw es;
}
}
Model Code
===================
public class Carrer
{
[Required]
[Display(Name = "GroupId")]
public string strGroupId { get; set; }
[Required]
[Display(Name = "GroupName")]
public string strGroupName { get; set; }
[Display(Name = "Select Image")]
public string SelectImage { get; set; }
[Required]
[Display(Name = "Choose File")]
public HttpPostedFileBase file { get; set; }
}
}
}
}
我尝试过:
现在我的代码仅用于数据库中的图像上传。我不能在另一个页面中显示数据库图像..,请帮助任何人
What I have tried:
Now my code is only for image uploading in database. i can't do displaying database images in another Page.., pls help anyone
推荐答案
( document ).on( 点击, #btnid, function (event){
event.preventDefault();
var fileOptions = {
success:res,
dataType: < span class =code-string> json
}
(document).on("click", "#btnid", function (event) { event.preventDefault(); var fileOptions = { success: res, dataType: "json" }
( #formid)。ajaxSubmit(fileOptions);
});
< / script >
< script src = // code.jquery.com/jquery-1.11.2.min.js\" 类型 = text / javascript > < / script >
< script type = text / javascript >
function ShowImagePreview(输入){
if (input.files&& input.files [ 0 ]){
var reader = new FileReader();
reader.onload = function (e){
("#formid").ajaxSubmit(fileOptions); }); </script> <script src="//code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script> <script type="text/javascript"> function ShowImagePreview(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) {
(' #<%= ImgPrv.ClientID%>')。prop(' < span class =code-string> src',e.target.result)
.width( 240 )
。 height( 150 );
};
reader.readAsDataURL(input.files [ 0 ]);
}
}
< / script >
< div id = 对话框 >
@ Html.ValidationMessage(DuplicateGroup )
@ Html.ValidationMessage(GroupSaved)
< / div >
@using(Html.BeginForm(SubmitImage,Carrer,FormMethod.Post,new {enctype =multipart / form-data }))
{
@ Html.AntiForgeryToken()
@ Html.ValidationSummary(true)
< < span class =code-leadattribute> fieldset>
< div class = float-left >
< < span class =code-leadattribute> div id = 对话框 >
@ Html.ValidationMessage( DuplicateImage)
@ Html.ValidationMessage(ImageSaved)
< / div >
< center >
< h2 > 提交图片< / h2 >
< / center >
< div class = 编辑标签 >
@ Html.LabelFor(Model => Model.strGroupId)
< / div >
< div class = editor-field >
@ Html.EditorFor(Model => Model.strGroupId)
< div id = 对话框 >
@ Html.ValidationMessageFor(Model => Model.strGroupId)
< / div 跨度> < span class =code-keyword>>
< / div >
< div class = 编辑标签 >
@ Html.LabelFor(Model => Model.strGroupName)
< / div >
< div class = editor-field >
@ Html.EditorFor(Model => Model.strGroupName)
< div id = 对话框 >
@ Html.ValidationMessageFor(Model => Model.strGroupName)
< / div >
< / div >
< div class = editor-label >
@ Html.LabelFor(Model => Model.SelectImage)
< / div >
< input type = file name = file id =\"file\" />
<div id=\"dialog\">
@Html.ValidationMessage(\"CustomError\")
</div>
<center>
<input type=\"submit\" value=\"Upload\" />
</center>
</div>
</fieldset>
}
@Scripts.Render(\"~/bundles/jqueryval\")
('#<%=ImgPrv.ClientID%>').prop('src', e.target.result) .width(240) .height(150); }; reader.readAsDataURL(input.files[0]); } } </script> <div id="dialog"> @Html.ValidationMessage("DuplicateGroup") @Html.ValidationMessage("GroupSaved") </div> @using (Html.BeginForm("SubmitImage", "Carrer", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <div class="float-left"> <div id="dialog"> @Html.ValidationMessage("DuplicateImage") @Html.ValidationMessage("ImageSaved") </div> <center> <h2>Submit Image</h2> </center> <div class="editor-label"> @Html.LabelFor(Model => Model.strGroupId) </div> <div class="editor-field"> @Html.EditorFor(Model => Model.strGroupId) <div id="dialog"> @Html.ValidationMessageFor(Model => Model.strGroupId) </div> </div> <div class="editor-label"> @Html.LabelFor(Model => Model.strGroupName) </div> <div class="editor-field"> @Html.EditorFor(Model => Model.strGroupName) <div id="dialog"> @Html.ValidationMessageFor(Model => Model.strGroupName) </div> </div> <div class="editor-label"> @Html.LabelFor(Model => Model.SelectImage) </div> <input type="file" name="file" id="file" /> <div id="dialog"> @Html.ValidationMessage("CustomError") </div> <center> <input type="submit" value="Upload" /> </center> </div> </fieldset> } @Scripts.Render("~/bundles/jqueryval")
Controller code
====================
Controller code
====================
public class CarrerController : Controller
{
//
// GET: /Carrer/
public ActionResult SubmitImage()
{
return View();
}
[HttpPost]
//public ActionResult SubmitImage(HttpPostedFileBase file, Carrer model)
public ActionResult SubmitImage(Carrer model)
{
//string blnImageUploaded;
if (model.file != null && model.file.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/UploadImages"),
Path.GetFileName(model.file.FileName));
model.file.SaveAs(path);
InsertMapDetails(model, path);
//if (blnImageUploaded == true)
//{
ViewBag.Message = "File uploaded successfully";
//}
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.Message = "You have not specified a file.";
}
return View();
}
public ActionResult Save(FormCollection formCollection)
{
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
}
return View();
}
public bool checkImageUploated(string strGroupId, string strGroupName, string strFullPath) //This method checks the valid image is uploaded in table or not.
{
bool blnValidImage = false;
string connString = ConfigurationManager.ConnectionStrings["DBconnectionString"].ConnectionString; // Read the connection string from the web.config file
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("Update MAP set IMAGEPATH = '" + strFullPath + "' where GROUPID = '" + strGroupId + "' and GROUPNAME = '" + strGroupName + "' ", conn);
blnValidImage = Convert.ToBoolean(cmd.ExecuteNonQuery());
return blnValidImage;
}
}
public string InsertMapDetails(Carrer model, string strFullPath)
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBconnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert into MAP (GROUPID,GROUPNAME,IMAGEPATH) values('" + model.strGroupId.Trim() + "','" + model.strGroupName.Trim() + "','" + strFullPath + "')";
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return "Success";
}
catch (Exception es)
{
throw es;
}
}
Model Code
===================
public class Carrer
{
[Required]
[Display(Name = "GroupId")]
public string strGroupId { get; set; }
[Required]
[Display(Name = "GroupName")]
public string strGroupName { get; set; }
[Display(Name = "Select Image")]
public string SelectImage { get; set; }
[Required]
[Display(Name = "Choose File")]
public HttpPostedFileBase file { get; set; }
}
}
}
}
What I have tried:
Now my code is only for image uploading in database. i can’t do displaying database images in another Page.., pls help anyone
What I have tried:
Now my code is only for image uploading in database. i can't do displaying database images in another Page.., pls help anyone
这篇关于如何获取数据库图像并在ASP.NET MVC 4中显示另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!