Image uploading in images folder issue in Asp.net - c#

I am trying to upload JPG file to a folder I have created in my project.
The image does not get saved in the images folder. It displays my image when I upload but the image itself is not present in images folder.
Here is the code i am using:
private void btnUpload_Click(object sender, System.EventArgs e)
{
// Initialize variables
string sSavePath;
string sThumbExtension;
int intThumbWidth;
int intThumbHeight;
// Set constant values
sSavePath = "images/";
sThumbExtension = "_thumb";
intThumbWidth = 160;
intThumbHeight = 120;
// If file field isn’t empty
if (filUpload.PostedFile != null)
{
// Check file size (mustn’t be 0)
HttpPostedFile myFile = filUpload.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
lblOutput.Text = "No file was uploaded.";
return;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
lblOutput.Text = "The file must have an extension of JPG";
return;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData,0,nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData,0, myData.Length);
newFile.Close();
// Check whether the file is really a JPEG by opening it
System.Drawing.Image.GetThumbnailImageAbort myCallBack =
new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap myBitmap;
try
{
myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));
// If jpg file is a jpeg, create a thumbnail filename that is unique.
file_append = 0;
string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ sThumbExtension + ".jpg";
while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
{
file_append++;
sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) +
file_append.ToString() + sThumbExtension + ".jpg";
}
// Save thumbnail and output it onto the webpage
System.Drawing.Image myThumbnail
= myBitmap.GetThumbnailImage(intThumbWidth,
intThumbHeight, myCallBack, IntPtr.Zero);
myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
imgPicture.ImageUrl = sSavePath + sThumbFile;
// Displaying success information
lblOutput.Text = "File uploaded successfully!";
// Destroy objects
myThumbnail.Dispose();
myBitmap.Dispose();
}
catch (ArgumentException errArgument)
{
// The file wasn't a valid jpg file
lblOutput.Text = "The file wasn't a valid jpg file.";
System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
}
}
}
public bool ThumbnailCallback()
{
return false;
}

I'd be surprised if the line myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile)); works...
You are trying to map a file which doesn't exist yet!
Try
myThumbnail.Save(Server.MapPath(sSavePath) + sThumbFile));

Related

A generic error occured in GDI+ while saving image

I have to save an image in post request in byte64String format
when i save that image i get A generic error occurred in GDI+
here is my code
byte[] ix = Convert.FromBase64String(obj.Image);
var ID = obj.Id;
using (var mStream = new MemoryStream(ix))
{
var img = Image.FromStream(mStream);
var image = obj.ImageName + ".jpg";
string path = HostingEnvironment.MapPath("/Images/" + ImageType + "/" + ID + "/" + image);
System.IO.Directory.CreateDirectory(path);
try
{
img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
var d = e;
}
}
also
this is not a permission issue as i am able to create text files in the same directory
Quite simply you are confusing paths and filenames.
The problem if could hazzard a guess, you probably have a folder that is your filename, and you are trying to save a file with that same name, which windows forbids
Your code tweaked
var image = $"{obj.ImageName }.jpg";
// get the path, and only the path
string path = HostingEnvironment.MapPath($"/Images/{ImageType}/{ID}/");
// Create directory if needed (from that path)
Directory.CreateDirectory(path,image);
...
// now create the correct full path
var fullPath = Path.Combine(path,fileName);
// save
img.Save(fullPath, ImageFormat.Jpeg);

how to get FileName, FilePath to Store it in a Variabl and then upload that file in asp.net

I want to merge two files and save it is as new file.
e.g
a1,a2 new a3
...and then upload that file which i have merge which is a3.
I mean I am saving a file in a folder , i want when i save , i get exactly that f filename as well filepath.
here is my code.
protected void Button1_Click(object sender, EventArgs e)
{
string fname = "";
if (txtFile.HasFile)
{
try
{
HttpFileCollection uploadedFiles = Request.Files;
// Get the HttpFileCollection
string[] filespath = new string[15];
for (int i = 0; i < uploadedFiles.Count; i++)
{
HttpPostedFile hpfiles = uploadedFiles[i];
fname = Path.GetFileName(hpfiles.FileName);
if (hpfiles.ContentLength > 0)
{
hpfiles.SaveAs(Server.MapPath("~/Images/") + Path.GetFileName(hpfiles.FileName));
hpfiles.SaveAs(Server.MapPath(Path.Combine(#"~/Images/", fname)));
string filepath = Server.MapPath(#"~/Images/");
string path = filepath + fname;
filespath[i] = path;
}
}
// MergeFiles(#"C:\ENROLLDOCS\New Document.pdf"+DateTime.Now.ToFileTime(), filespath);
MergeFiles(#"D:\Razim\MedFlow\tempp\New Document.pdf" + " " + DateTime.Now.ToFileTime() + ".pdf", filespath);
// now i want to get the filename and filepath which i have merged and saved, for uploading.
}
catch (Exception ex)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
iTextSharp is a C# PDF library that can read and write PDF's based on the iText library, it's free for open source... paid for commercial use. Here is an existing example of how to merge two PDF's using their library, you can easily adapt it to the file upload scenario.
Merging multiple PDFs using iTextSharp in c#.net

OutOfMemoryException error in Loop

I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}

Read Image file metadata

I want to upload an image file and then extract its basic information (author, dimensions, date created, modified, etc) and display it to the user. How can I do it.
A solution or reference to this problem in asp.net c# code would be helpful. But javascript or php would be ok as well.
Check this Link. You will get more Clearance about GetDetailsOf() and its File Properties based on the Win-OS version wise.
If you want to use C# code use below code to get Metadata's:
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
C# solution could be found here:
Link1
Link2
Bitmap image = new Bitmap(fileName);
PropertyItem[] propItems = image.PropertyItems;
foreach (PropertyItem item in propItems)
{
Console.WriteLine("iD: 0x" + item.Id.ToString("x"));
}
MSDN Reference
C# Tutorial Reference
try this...
private string doUpload()
{
// Initialize variables
string sSavePath;
sSavePath = "images/";
// Check file size (mustn’t be 0)
HttpPostedFile myFile = FileUpload1.PostedFile;
int nFileLen = myFile.ContentLength;
if (nFileLen == 0)
{
//**************
//lblOutput.Text = "No file was uploaded.";
return null;
}
// Check file extension (must be JPG)
if (System.IO.Path.GetExtension(myFile.FileName).ToLower() != ".jpg")
{
//**************
//lblOutput.Text = "The file must have an extension of JPG";
return null;
}
// Read file into a data stream
byte[] myData = new Byte[nFileLen];
myFile.InputStream.Read(myData, 0, nFileLen);
// Make sure a duplicate file doesn’t exist. If it does, keep on appending an
// incremental numeric until it is unique
string sFilename = System.IO.Path.GetFileName(myFile.FileName);
int file_append = 0;
while (System.IO.File.Exists(Server.MapPath(sSavePath + sFilename)))
{
file_append++;
sFilename = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
+ file_append.ToString() + ".jpg";
}
// Save the stream to disk
System.IO.FileStream newFile
= new System.IO.FileStream(Server.MapPath(sSavePath + sFilename),
System.IO.FileMode.Create);
newFile.Write(myData, 0, myData.Length);
newFile.Close();
return sFilename;
}

Upload image, rename it, make thumbnail and replace the original. (optimization)

I have created these functions which I described in the question. However I think the way I did it is not the optimal way of doing it.
[HttpPost]
public ActionResult Create(FormCollection collection, string schooljaarparam, FlatONASAanbieder foa) {
if (ModelState.IsValid) {
// var r = new List<ViewDataUploadFilesResult>();
foreach (string file in Request.Files) {
HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
//extensie nakijken. jpg, png, jpeg, of GIF.
if (MvcApplication.isImage(hpf.FileName)) {
//Image img = new Image();
string savedFileName = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory + "uploads\\ONAS\\",
Path.GetFileName(hpf.FileName));
FileInfo fi = new FileInfo(savedFileName);
int i = 1;
while (fi.Exists) {
fi = new FileInfo(savedFileName.Substring(0, savedFileName.Length - Path.GetFileName(savedFileName).Length) + Path.GetFileNameWithoutExtension(savedFileName) + " (" + i++ + ") " + Path.GetExtension(savedFileName));
}
savedFileName = fi.DirectoryName + "\\" + fi.Name;
hpf.SaveAs(savedFileName);
using (Image Img = Image.FromFile(savedFileName)) {
//Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 79);
Size NewSize = VerkleinMaxHoogte(Img.Size, 79);
using (Image ImgThnail = new Bitmap(Img, NewSize.Width, NewSize.Height)) {
//string ss = savedFileName.Substring(0, savedFileName.Length - Path.GetFileName(savedFileName).Length) + Path.GetFileNameWithoutExtension(savedFileName) + "-thumb" + Path.GetExtension(savedFileName);
ImgThnail.Save(savedFileName + ".tmp", Img.RawFormat);
ImgThnail.Dispose();
}
Img.Dispose();
}
System.IO.File.Delete(savedFileName);
FileInfo f = new FileInfo(savedFileName + ".tmp");
f.MoveTo(savedFileName);
} else {
ModelState.AddModelError("ONAS_Logo", "Het geuploadde bestand is geen afbeelding. ");
}
//r.Add(new ViewDataUploadFilesResult() {
// Name = savedFileName,
// Length = hpf.ContentLength
//});
}
}
// return View("UploadedFiles", r);
return View();
}
[NonAction]
public Size VerkleinMaxHoogte(Size orig, double height) {
double tempval = height / orig.Height;
return new Size(Convert.ToInt32(tempval * orig.Width), Convert.ToInt32(height));
}
in global.asax
public static bool isImage(string s) {
if (s.EndsWith(".jpg", true, null) || s.EndsWith(".jpeg", true, null) || s.EndsWith(".gif", true, null) || s.EndsWith(".png", true, null)) {
return true;
}
return false;
}
so the way I do it:
I get the file from the browser
I check if it is an Image
I check if the file exists, and if so, change the filename accordingly
I save the file on disk (IO, slow)
I open the file as an image
I calculate the width and height with the VerkleinMaxHoogte method
I create the thumbnail and save it with a tmp extension
I delete the original file
I rename the thumbnail to the original file name (this is what I want)
How do I do it faster?
You can always use HttpPostedFile.InputStream and Image.FromStream method to combine #4 & #5. This will also eliminate #8 & #9.

Categories

Resources