如何在Web应用程序中上载图像并将其存储在数据库中 [英] how to upload an image in a web app and store the same in a database
问题描述
我使用visual studio 2012在框架4.5中创建了一个asp.net mvc 4 Web应用程序。在此我创建了一个数据库,用于存储我想要为我的客户提供的项目。我想允许我的用户上传他们的产品详细信息以供销售。为此,
i)我希望他们输入产品的详细信息及其图像。
ii)我想将上传的图像存储在项目内的文件夹中。
iii)我想将这个图像的位置存储在数据库中
或者它们是否有任何其他方式来存储图像用户上传的数据库。记住它不是一个网站,它是一个MVC4的web应用程序
提前谢谢
I have created an asp.net mvc 4 web application in framework 4.5 using visual studio 2012. In this i have created a database which stores the items that i want offer my clients. I want to allow my users to upload their products details too for sale. For this,
i)I want them to enter the details of their products along with its image.
ii)i want to store the images uploaded in a folder inside my project.
iii) i want to store the location of this image in the database
or if their is any other way to store images in the database that are uploaded by users. Remember it is not a website, it is a web application of MVC4
Thanks in advance
推荐答案
首先,在你的.cshtml文件中使用文件控制器
Firstly, in your .cshtml file use a file controler
@using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-group">
<input type="file" id="fileToUpload" name="file" />
<span class="field-validation-error" id="spanfile"></span>
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-info" id="UploadFile" name="action" />
</div>
}
现在在您的控制器中验证文件,获取字节数组并将其存储在数据库中。< br $> b $ b
now in your controller validate the file, get the byte array and store it n the db.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> UploadFile(HttpPostedFileBase file, CustomModel model)
{
if (ModelState.IsValid)
{
if (file == null)
{
ModelState.AddModelError(string.Empty, "please upload a file");
}
else if (file.ContentLength > 0)
{
// check if its a valid image type
// get the byte array
byte[] byteArray = file.ToByteArray();
// Store this byte array in db
}
}
return View(model);
}
这篇关于如何在Web应用程序中上载图像并将其存储在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!