MVC3 uploadify uploading images to folders - image

I am using uploadify for uploading multiple images with progress in ASP.NET MVC3 and I want to upload lets say from url Gallery/Upload/2 to folder with name 2 and Gallery/Upload/3 to folder 3 and so on. I just don´t know how. For get working uploading I used this sample and modified sample upload script to this:
public string Upload(HttpPostedFileBase fileData)
{
var id = 2;
var fotka = new Photo();
fotka.GalleryId = id;
fotka.Description = fileData.FileName;
fotka.Name = fileData.FileName;
db.Photos.Add(fotka);
db.SaveChanges();
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileData.FileName);
var fileName = Path.GetFileName(fileData.FileName);
string path = Server.MapPath("~/Fotky/") + id.ToString() + "\\" + fileNameWithoutExtension;
// var path = Path.Combine(Server.MapPath("~/Fotky/"), galleryId.ToString(), "/", fileNameWithoutExtension);
using (var input = new Bitmap(fileData.InputStream))
{
int width;
int height;
if (input.Width > input.Height)
{
width = 128;
height = 128 * input.Height / input.Width;
}
else
{
height = 128;
width = 128 * input.Width / input.Height;
}
using (var thumb = new Bitmap(width, height))
using (var graphic = Graphics.FromImage(thumb))
{
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
graphic.DrawImage(input, 0, 0, width, height);
System.IO.Directory.CreateDirectory(Server.MapPath("~/Fotky/") + id.ToString());
using (var output = System.IO.File.Create(path + "_small" + Path.GetExtension(fileName)))
{
thumb.Save(output, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
fileData.SaveAs(path + Path.GetExtension(fileName));
return "ok";
}
as you can see I am using id as 2 as default, but I want to get it from parameters, is it posible? And how? Thank you
No one knows answer? It´s really important for me

You could have your controller action take the id as action argument:
public string Upload(HttpPostedFileBase fileData, string id)
{
...
}
and then pass this id when configuring your plugin:
$("#fileuploader").fileUpload({
'uploader': '#Url.Content("~/Scripts/uploader.swf")',
'cancelImg': '#Url.Content("~/Images/cancel.png")',
'buttonText': 'Select Image',
'script': '#Url.Action("Upload", "Home", new { id = "2" })',
'folder': '#Url.Content("~/uploads")',
'fileDesc': 'Image Files',
'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
'multi': true,
'auto': true
});

Related

Image in ASP.NET MVC

I have form for upload file and i want to upload thumbnail for the file in the same form I am doing that with this part of code :
var basePath2 = Path.Combine(Directory.GetCurrentDirectory() + "\\Thumbnails\\");
bool basePathExists2 = System.IO.Directory.Exists(basePath2);
if (!basePathExists2)
Directory.CreateDirectory(basePath2);
var thumbnailPath = Path.Combine(basePath2, Thumbnail.FileName);
if (!System.IO.File.Exists(thumbnailPath))
{
using (var stream = new FileStream(thumbnailPath, FileMode.Create))
{
await Thumbnail.CopyToAsync(stream);
}
}
I am saving this model to the database:
var fileModel = new FileUploadViewModel
{
Year = createdOn,
PublishedOn = model.PublishedOn,
FileType = File.ContentType,
Extension = extension,
Name = model.Name,
Description = model.Description,
FilePath = filePath,
Author = model.Author,
ThumbnailPath = thumbnailPath,
};
When I want to show the thumbnail in a view, it doesn't work but in src I have the right path, as you can see in this screenshot:
Screenshot with Source of image
In controller :
string uniqueThumbName = null;
if (Thumbnail != null)
{
string uploadsFolder = Path.Combine(hostingEnvironment.WebRootPath, "Thumbnails");
uniqueThumbName=Guid.NewGuid().ToString() + "_" + Thumbnail.FileName;
string filePath2 = Path.Combine(uploadsFolder, uniqueThumbName);
Thumbnail.CopyTo(new FileStream(filePath2, FileMode.Create));
}
var fileModel = new FileUploadViewModel
{
ThumbnailPath=uniqueThumbName,
};
In View :
var thumbPath = "~/Thumbnails/" + file.ThumbnailPath;
<img style="width:80px;height:80px;" src="#thumbPath" asp-append-version="true" />

Rotativa BuildFile not hitting the Action Method

I have two action methods in my Controller class:
DetailsAll: to get some data and display in the view
SaveAsPDF: Called on windows.load of DetailsAll.cshtml which should save DetailsAll view as pdf
My issue is in SaveAsPDF Action method. Here I am trying to use Rotativa ActionAsPdf and subsequently BuildFile methods to generate and save the PDF. However, when executing the line "BuildFile", it is not hitting the breakpoint in my DetailsAll Action method, subsequently causing the PDF to be generated blank.
Could you please help where I am going wrong?
[HttpGet]
public ActionResult DetailsAll()
{
var selectionBuilder = builderFactory.GetGeocodeReportSelectionViewModelBuilder();
var companyList = selectionBuilder.Build();
List<GeocodeReportViewModel> viewModel = new List<GeocodeReportViewModel>();
foreach(SelectListItem record in companyList.Companies)
{
var builder = builderFactory.GetGeocodeReportViewModelBuilder(int.Parse(record.Value));
viewModel.Add(builder.Build());
}
var model = new AllGeocodeReportViewModel
{
GeocodeReports = viewModel
};
return View(model);
}
[HttpGet]
public string SaveAsPDF()
{
var report = new ActionAsPdf("DetailsAll")
{
FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMYY") + ".pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Landscape,
PageMargins = { Left = 1, Right = 1 }
};
byte[] pdf = report.BuildFile(ControllerContext);
System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
return "true";
}
Finally found the issue after extensive search. I need to send Authentication cookies along with the BuildFile request for this to work. Added the below code and it generates PDF correctly now:
public void SaveAsPDF()
{
var cookies = Request.Cookies.AllKeys.ToDictionary(k => k, k => Request.Cookies[k].Value);
var report = new ActionAsPdf("DetailsAll")
{
FileName = "OEM_GeocodeReport_" + System.DateTime.Now.ToString("MMyy") + ".pdf",
PageSize = Size.A4,
PageOrientation = Orientation.Portrait,
PageMargins = { Left = 3, Right = 3 },
FormsAuthenticationCookieName = System.Web.Security.FormsAuthentication.FormsCookieName,
Cookies = cookies
};
byte[] pdf = report.BuildFile(ControllerContext);
System.IO.File.WriteAllBytes("C:\\" + report.FileName, pdf);
}

Add Image in Word Open SDK + dotnet core

I am trying to add an image to the word document using dotnet core and Open SDK library. Followed the exact same instruction as per the MSDN article. The code runs ok, but while trying to open document its says the document is corrupted.
Microsoft Doc
Used the OpenSDK Productivity tool and validated the document. Showing this error
Have confirmed that the Image Type are same. Not able to understand whats wrong.
private const string RefrenceKeyWord = "rId";
static void Main(string[] args)
{
InsertAPicture(document, fileName);
}
public static void InsertAPicture(string document, string fileName)
{
Int64Value imageWidth = 5731510L;
Int64Value imageHeight = 3820795L;
//using (var image = new Bitmap(fileName))
//{
// imageWidth = image.GetWidthInEMUs() / 10;
// imageHeight = image.GetHeightInEMUs() / 10;
//}
using (WordprocessingDocument wordprocessingDocument =
WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Png);
using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}
//## start of new Code ##
var maxId = mainPart.Parts
.Where(p => p.RelationshipId.StartsWith(RefrenceKeyWord))
.Select(p =>
Convert.ToInt32(p.RelationshipId.Replace(RefrenceKeyWord,
"")))
.Max();
mainPart.ChangeIdOfPart(imagePart, $"{RefrenceKeyWord}{maxId + 1}");
//## end of new Code ##
AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), imageWidth, imageHeight);
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, Int64Value width, Int64Value height)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = width, Cy = height },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 2540L,
BottomEdge = 8255L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1",
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "Picture 1"
},
new PIC.NonVisualPictureDrawingProperties(new A.PictureLocks() { NoChangeAspect = true, NoChangeArrowheads = true })),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}",
})
)
{
Embed = relationshipId,
//CompressionState =
//A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = width, Cy = height }),
new A.PresetGeometry(
new A.AdjustValueList()
)
{ Preset = A.ShapeTypeValues.Rectangle }))
)
{ Uri = "https://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
SectionProperties sectPr = (SectionProperties)wordDoc.MainDocumentPart.Document.Body.ChildElements.Last();
// var p = wordDoc.MainDocumentPart.RootElement;
// var p1 = wordDoc.MainDocumentPart.Document.Body.FirstChild;
var p1 = new Paragaph(new Run(element));
// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.InsertBefore(p1, sectPr);
}

Inserted image not displayed in OpenXml created Word document

I'm trying to insert a signature image in a Word document created by a standard-letter generating application. I am using code adapted from various examples found on the web (see below). The application inserts the image, and the space in the document occupied by it is correct, but the image itself is not displayed.
I have tried it with both .png and .jpg images, but neither work; it doesn't appear to be a problem with the image itself.
I have examined the document using the OpenXml SDK Tool, which shows that the image is correctly embedded and encoded as a Base64 data string.
The problem that the SDK Tool does identify is that, compared to a document in which an image is manually inserted (and is correctly displayed), the pic:pic element in the document is rendered with the wrong namespace (a:pic) and it and all child controls are rendered as OpenXmlUnknownElement (see screenshot below).
Can anyone please tell me what is causing the incorrect namespace / element, and how to fix the problem?
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Drawing;
using System.Drawing.Imaging;
...
using A = DocumentFormat.OpenXml.Drawing;
using A14 = DocumentFormat.OpenXml.Office2010.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
using WP = DocumentFormat.OpenXml.Wordprocessing;
private void ReplacePlaceholderWithImage(MainDocumentPart mainDocumentPart, OpenXmlElement placeholder, string imagePath)
{
if (placeholder != null)
{
ImagePart ip = AddImagePart(mainDocumentPart, imagePath);
string relationshipId = mainDocumentPart.GetIdOfPart(ip);
var drawing = GetDrawing(relationshipId, imagePath);
placeholder.InsertAfterSelf(new WP.Paragraph(new WP.Run(drawing)));
placeholder.Remove();
Console.WriteLine("Picture inserted into picture content control successfully");
}
}
private ImagePart AddImagePart(MainDocumentPart mainDocumentPart, string imagePath)
{
var partType = GetPartTypeForImage(imagePath);
ImagePart ip = mainDocumentPart.AddImagePart(partType);
using (FileStream fileStream = File.Open(imagePath, FileMode.Open))
{
ip.FeedData(fileStream);
}
return ip;
}
private OpenXmlElement GetDrawing(string relationshipId, string imagePath)
{
//calculate dimensions
var size = GetImageDimensions(imagePath);
// Define the reference of the image.
return
new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = size.Width,
Cy = size.Height
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = Path.GetFileName(imagePath)
},
new PIC.NonVisualPictureDrawingProperties()),
new A.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
}))
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(new A.FillRectangle())),
new A.ShapeProperties(
new A.Transform2D(new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = size.Width, Cy = size.Width }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});
}
private ImagePartType GetPartTypeForImage(string imagePath)
{
var img = GetImage(imagePath);
if (img.RawFormat.Equals(ImageFormat.Gif))
{
return ImagePartType.Gif;
}
else if (img.RawFormat.Equals(ImageFormat.Png))
{
return ImagePartType.Png;
}
else if (img.RawFormat.Equals(ImageFormat.Jpeg))
{
return ImagePartType.Jpeg;
}
else
{
throw new ApplicationException("Unexpected image type");
}
}
this issue stressed me up some hours and finally I found the reason. That's because the Drawing element Id need to be unique, you can't fix the ID like this
new DW.DocProperties() { Id = 1U, Name = "Picture 1" }
In my case, I have this function to set alt text and update the Id as well:
private static HashSet<uint> _drawingElementIds = new HashSet<uint>();
public static void SetPictureAltText(OpenXmlElement imageContainer, string altText)
{
var docPro = imageContainer.Descendants<DocProperties>().FirstOrDefault();
if (docPro != null)
{
//Make sure new image has unique ID, otherwise some images won't display
var newId = (uint)new Random().Next(10, 10000);
while (_drawingElementIds.Contains(newId))
{
newId = (uint)new Random().Next(10, 10000);
}
_drawingElementIds.Add(newId);
docPro.Id = new UInt32Value(newId);
docPro.Description = altText;
}
}
Cheers,
Nick
Watch your namespaces! I'm guessing you've copied from the same source as I did (which I'm sure was the Microsoft documentation), however the namespaces appear to be wrong in it for the following two properties:
A.BlipFill -> PIC.BlipFill
A.ShapeProperties -> PIC.ShapeProperties
Full code below:
var element = new Drawing(
new DW.Inline(
new DW.Extent()
{
Cx = 5657850L,
Cy = 3771900L
},
new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L },
new DW.DocProperties() { Id = 1U, Name = "Picture 1" },
new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true, NoResize = true, NoSelection = true }),
new A.Graphic(new A.GraphicData(new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = 0U,
Name = "image.png"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
}))
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = 5657850L, Cy = 3771900L }),
new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle })))
{
Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
}))
{
DistanceFromTop = 0U,
DistanceFromBottom = 0U,
DistanceFromLeft = 0U,
DistanceFromRight = 0U,
EditId = "50D07946"
});

How Upload Multiple files (images)(more than 100 files at a time) in mvc4?

Hi all i ma working on mvc4 i had uploaded single image (file) but now i need to uoload more than 100 files(images) at time to my application how could i do this plz help to do this
here my code:
this is my controllers
[HttpPost]
public ActionResult Uploading(ImageModel model)
{
if (ModelState.IsValid)
{
string fileName = Guid.NewGuid().ToString();
string serverPath = Server.MapPath("~");
string imagesPath = serverPath + "Content\\Images\\";
string thumsise = Path.Combine(imagesPath, "Thumb" + fileName);
string thumbPath = Path.Combine(imagesPath, "Thu" + fileName);
string fullPath = Path.Combine(imagesPath, "Full" + fileName);
string Bigpath = Path.Combine(imagesPath, "big" + fileName);
string Bigpatha = Path.Combine(imagesPath, "biga" + fileName);
string Bigpathb = Path.Combine(imagesPath, "bigb" + fileName);
string Bigpathc = Path.Combine(imagesPath, "bigc" + fileName );
ImageModel.ResizeAndSave(thumsise, fileName, model.ImageUploaded.InputStream, 80, true);
ImageModel.ResizeAndSave(thumbPath, fileName, model.ImageUploaded.InputStream, 100, true);
ImageModel.ResizeAndSave(fullPath, fileName, model.ImageUploaded.InputStream, 500, true);
ImageModel.ResizeAndSave(Bigpath, fileName, model.ImageUploaded.InputStream, 200, true);
ImageModel.ResizeAndSave(Bigpatha, fileName, model.ImageUploaded.InputStream, 250, true);
ImageModel.ResizeAndSave(Bigpathb, fileName, model.ImageUploaded.InputStream, 150, true);
ImageModel.ResizeAndSave(Bigpathc, fileName, model.ImageUploaded.InputStream, 50, true);
}
return View("Upload",model);
}
this my class file:
public class ImageModel
{
[Required]
public HttpPostedFileWrapper ImageUploaded { get; set; }
public static void ResizeAndSave(string savePath, string fileName, Stream imageBuffer, int maxSideSize, bool makeItSquare)
{
int newWidth;
int newHeight;
Image image = Image.FromStream(imageBuffer);
int oldWidth = image.Width;
int oldHeight = image.Height;
Bitmap newImage;
if (makeItSquare)
{
int smallerSide = oldWidth >= oldHeight ? oldHeight : oldWidth;
double coeficient = maxSideSize / (double)smallerSide;
newWidth = Convert.ToInt32(coeficient * oldWidth);
newHeight = Convert.ToInt32(coeficient * oldHeight);
Bitmap tempImage = new Bitmap(image, newWidth, newHeight);
int cropX = (newWidth - maxSideSize) / 2;
int cropY = (newHeight - maxSideSize) / 2;
newImage = new Bitmap(maxSideSize, maxSideSize);
Graphics tempGraphic = Graphics.FromImage(newImage);
tempGraphic.SmoothingMode = SmoothingMode.AntiAlias;
tempGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
tempGraphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
tempGraphic.DrawImage(tempImage, new Rectangle(0, 0, maxSideSize, maxSideSize), cropX, cropY, maxSideSize, maxSideSize, GraphicsUnit.Pixel);
}
else
{
int maxSide = oldWidth >= oldHeight ? oldWidth : oldHeight;
if (maxSide > maxSideSize)
{
double coeficient = maxSideSize / (double)maxSide;
newWidth = Convert.ToInt32(coeficient * oldWidth);
newHeight = Convert.ToInt32(coeficient * oldHeight);
}
else
{
newWidth = oldWidth;
newHeight = oldHeight;
}
newImage = new Bitmap(image, newWidth, newHeight);
}
newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
//newImage.Save(savePath + fileName + ".jpg", ImageFormat.Jpeg);
image.Dispose();
newImage.Dispose();
}
}
}
and this is my index page:
#using (Html.BeginForm("Uploading", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="ImageUploaded" id="btnUpload" multiple="multiple" accept="image/*" />
<button type="submit" id="Upload">Upload</button>
<br />
}
could u help me to upload more than 100 files at a time thanks in advance
The view is OK. The problem is the controller: don't use ImageModel to get the file from the form. It restricts you to just one file. You can get multiple files through Request.Files property:
for (int i = 0; i < Request.Files.Count; i++)
{
if (Request.Files[i].ContentLength > 0)
{
HttpPostedFileBase uploadedFile = Request.Files[i];
... here you can use the resize and other logic
... on uploadedFile.InputStream
}
}
Check the HttpPostedFileBase class. It's the base class for HttpPostedFileWrapper which you use in your ImageModel model class.

Resources