无法上传与asp.net的MVC多个数据库图像 [英] unable to upload multiple db images with asp.net mvc
问题描述
我想几个分贝上传图片到SQL Server的2008R2。我在C#中使用ASP.NET MVC 3。正在发生的事情是,我得到显示的图像,但问题是,第二图像被显示为两倍。因此,它是重复的。我不知道为什么没有显示的第一张图像。
I am trying to upload several db images onto the SQL Server 2008R2. I am using ASP.NET MVC 3 in C#. What is happening is that I getting the images displayed but the problem is that the second image is being displayed as twice. So it is duplicate. I am not sure why the first image is not being displayed.
我SubProductCategory4表有以下几列(为简单起见)...
My SubProductCategory4 Table has the following columns (for simplicity sake)...
列名称:和Image1的IMAGE2有数据类型VARBINARY(MAX),另一列名称:ImageMimeType有数据类型为varchar(50)
Column Names: Image1 and Image2 has DataTypes varbinary(MAX), another column Name: ImageMimeType has DataTypes varchar(50).
我的控制器具有以下code的创建方法...
My Controller has the following code for Create method...
[HttpPost]
public ActionResult Create([Bind(Exclude = "SubProductCategoryFourID")] SubProductCategory4 Createsubcat4, IEnumerable<HttpPostedFileBase> files, FormCollection collection)
{
if (ModelState.IsValid)
{
foreach (string inputTagName in Request.Files)
{
if (Request.Files.Count > 0) // tried Files.Count > 1 did
// not solve the problem
{
Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
// var fileName = Path.GetFileName(inputTagName);
//var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
}
// moved db.AddToSubProductCategory4(Createsubcat4);
// here but did not solve the problem
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
return RedirectToAction("/");
}
//someother code
return View(Createsubcat4);
}
getImage方法...
GetImage method...
public FileResult GetImage(int id)
{
const string alternativePicturePath = @"/Content/question_mark.jpg";
MemoryStream stream;
MemoryStream streaml;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if ((z != null && z.Image1 != null) && (z != null && z.Image2 != null))
{
stream = new MemoryStream(z.Image1);
streaml = new MemoryStream(z.Image2);
}
else
{
var path = Server.MapPath(alternativePicturePath);
foreach (byte item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
}
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
/* streaml = new MemoryStream();
var imagey = new System.Drawing.Bitmap(path);
imagey.Save(streaml, System.Drawing.Imaging.ImageFormat.Jpeg);
streaml.Seek(0, SeekOrigin.Begin);*/
}
return new FileStreamResult(stream,"image/jpg");
}
FileHandler.cs
FileHandler.cs
public class FileHandler
{
public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
{
int nFileLen = file.ContentLength;
byte[] result = new byte[nFileLen];
file.InputStream.Read(result, 0, nFileLen);
return result;
}
}
create.cshtml ...
create.cshtml...
@using (Html.BeginForm("Create", "ProductCategoryL4", "GetImage",
FormMethod.Post, new { enctype = "multipart/form-data" }))
//some code then...
<div class="editor-field">
@Html.EditorFor(model => model.Image1)
<input type="file" id="fileUpload1" name="fileUpload1" size="23"/>
@Html.ValidationMessageFor(model => model.Image1)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Image2)
<input type="file" id="fileUpload2" name="fileUpload2" size="23"/>
@Html.ValidationMessageFor(model => model.Image2)
</div>
index.cshtml ...
index.cshtml...
<img src="@Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
<td>
<img src="@Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
我在C#中使用SQL Server 2008 R2使用VS2010使用,ASP.NET MVC3。在此先感谢,但请只有当你知道答案回应。如果有这样做的更好的方法,请让我知道。
I am using using VS2010, ASP.NET MVC3 in C# with SQL Server 2008R2. Thanks in advance but please only respond if you know the answer. If there is a better way of doing this please let me know.
推荐答案
在code所列出通过文件循环,并为每一个,同时设置 Image1的
和 IMAGE2
是同样的事情。当您上传2个文件,它们都显示为图像2,因为这是适用于这两个领域的最后一个影像。
The code that is listed is looping through the files, and for each one, setting both Image1
and Image2
to be the same thing. When you upload 2 files, they are both showing up as image 2 because that was the last image applied to both fields.
试着用更多的东西像这样的,它一次,如果有足够的图像设置字段来更换循环。
Try replacing the loop with something more like this, which sets the fields one at a time if there are enough images.
FileHandler fh = new FileHandler();
if (Request.Files.Count > 0)
{
Createsubcat4.Image1 = fh.uploadedFileToByteArray(Request.Files[0]);
}
if (Request.Files.Count > 1)
{
Createsubcat4.Image2 = fh.uploadedFileToByteArray(Request.Files[1]);
}
db.AddToSubProductCategory4(Createsubcat4);
如果您需要打开这个以允许在未来更多的图像,你要替换 Image1的
和 IMAGE2
与图像的采集领域,并再次使用你的循环在上传的文件集合添加每个图像。事情是这样的:
If you need to open this up to allow more images in the future, you'll want to replace the Image1
and Image2
fields with a collection of images, and use your loop again to add each image in the uploaded files collection. Something like this:
FileHandler fh = new FileHandler();
foreach (HttpPostedFileBase uploadedImage in Request.Files)
{
Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
编辑:
现在,你是正确保存图像,你需要看看你的getImage
行动第二次看。你会发现,你正确时,您指定作用的结果(返回新FileStreamResult(流图像/ JPG);
),这两个文件加载到内存中,但您可只会返回第一流。您需要一种方法要求何时返回第二个流。有一对夫妇的方式去了解这一点,添加其他输入参数指定加载或创建仅返回第二个中的第二操作的映像。
Now that you are saving the images correctly, you need to take a second look at your GetImage
action. You'll notice that you correctly load both files into memory, however when you specify your action result (return new FileStreamResult(stream,"image/jpg");
) you are only ever returning the first stream. You need a way to return the second stream when requested. There are a couple ways to go about this, add another input parameter to specify which image to load or create a second action that only returns the second one.
要创建两个动作设置,您的code会是这个样子:
To create the two action set up, your code would look something like this:
public ActionResult GetImage1(int id)
{
const string alternativePicturePath = @"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image1 != null)
{
stream = new MemoryStream(z.Image1);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
public ActionResult GetImage2(int id)
{
const string alternativePicturePath = @"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image2 != null) // the difference is here
{
stream = new MemoryStream(z.Image2); // the difference is also here
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
这些功能几乎是相同的,并可以很容易地制成1这需要一个参数来选择要加载的图像。
These functions are almost identical and can easily be made 1 which takes a parameter to select which image to load.
public ActionResult GetImage(int id, int? imageNum)
{
imageNum = imageNum ?? 0;
const string alternativePicturePath = @"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
byte[] imageData = null;
if (z != null)
{
imageData = imageNum == 1 ? z.Image1 : imageNum == 2 ? z.Image2 : null;
}
if (imageData != null)
{
stream = new MemoryStream(imageData);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
此功能会指定 imageNum
作为查询参数,如:
This function would specify the imageNum
as a query parameter like:
http://www.mydomain.com/controllerName/GetImage/ {ID}?imageNum = {imageNum}
这篇关于无法上传与asp.net的MVC多个数据库图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!