Resize image while uploading - asp.net

i am using file upload control for uploading images.
in that iam checking the condition,if Image.Width > 250 || Image.Height > 400 then i am resizing the image.
but it is giving the error
"The SaveAs method is configured to require a rooted path, and the path 'ProductImages/roman_sandals.jpg' is not rooted."
ProductImages is folder where i am saving image.
Can anyone find why this is giving error,my code is
string strBigServerPath = AppHardcodeValue.productImgPath;
string strFileName = "";
if (prodImg.HasFile)
{
strFileName = prodImg.PostedFile.FileName;
string uniqueNum = Convert.ToString(System.Guid.NewGuid());
string shortFileName = System.IO.Path.GetFileName(strFileName);
string Extension = System.IO.Path.GetExtension(prodImg.FileName);
string newFileName = shortFileName;
prodImg.SaveAs(Server.MapPath(strBigServerPath + newFileName));
using (System.Drawing.Image Img =
System.Drawing.Image.FromFile(Server.MapPath(strBigServerPath) + newFileName))
{
if (Img.Width > 250 || Img.Height > 400)
{
Size MainSize = new Size(250, 400);
using (System.Drawing.Image ImgThnail =
new Bitmap(Img, MainSize.Width, MainSize.Height))
{
prodImg.SaveAs(strBigServerPath + newFileName);
}
}
Img.Dispose();
}
string ThumbnailPath = Server.MapPath(AppHardcodeValue.productThumbImgPath) + newFileName;
using (System.Drawing.Image Img =
System.Drawing.Image.FromFile(Server.MapPath(strBigServerPath) + newFileName))
{
Size ThumbNailSize = new Size(50, 50);
using (System.Drawing.Image ImgThnail =
new Bitmap(Img, ThumbNailSize.Width, ThumbNailSize.Height))
{
ImgThnail.Save(ThumbnailPath, Img.RawFormat);
ImgThnail.Dispose();
}
Img.Dispose();
}
}

You can use
HostingEnvironment.ApplicationPhysicalPath
in this case, and combine it with your image path.
For example:
Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "ProductImages/roman_sandals.jpg");
which will give you a rooted path. The folder "ProductImages" has to be located in the applications directory.
See here for details: http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.applicationphysicalpath.aspx

Related

FileNotFoundException while uploading a image

My objective is User can choose an image from any place from their desktop and upload/tweet the same to twitter. I'm struggling to set the relative path to the imagePath variable.
The path (D Drive) were my image stored. While running the application it looks in different path. This throws an error System.IO.FileNotFoundException. I tried Server.MapPath too. Assist me to resolve it.
Solved the issue as following
string filePath; string imagePath = "";
if (imgFile == null)
{
imgFile = Request.Files["imgFile"];
}
if (imgFile.FileName != "")
{
filePath = Server.MapPath("~/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath = filePath + Path.GetFileName(imgFile.FileName);
imgFile.SaveAs(filePath);
imagePath = Path.Combine(Server.MapPath(#"~/Images/"), filePath);
}
File must be saved in the server location, try to replace the below instruction:
string imagePath=Path.Combine(Request.MapPath("~/"),fileName);
with the below instruction
var fileName = Path.GetFileName(file.FileName);
var imagePath = Path.Combine(Request.MapPath("~/"), fileName);
file.SaveAs(imagePath);
........
Cordially

How to save image in to folder or directory in ASP.NET

I have A image like this
imgScreenShot.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes);
instead of binding image to that imgScreenShot i have to save that in to either any folder in project or any directory please help me.
I believe you are trying to convert base64 image string to image.
Below is the code you can use to convert it to image :
public static Image LoadImage(string base64string)
{
byte[] bytes = Convert.FromBase64String(base64string); //Convert.FromBase64String("R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw==");
Image image;
using (MemoryStream ms = new MemoryStream(bytes))
{
image = Image.FromStream(ms);
}
return image;
}
You can then save image as follows :
Image image = UtilityHelper.LoadImage(ch.Message);
string imgname = ch.MobileNo + "_" + DateTime.UtcNow.ToString("yyyyMMddHHmmssfff") + ".jpg";
string filepath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~\\Images\\") + subPath + "\\" + imgname);
var image2 = new Bitmap(image);
image2.Save(filepath, ImageFormat.Jpeg);

File not found exception once deployed to Server

I am using the below code to Upload an Image file to a SharePoint Document Library. The code works fine locally but once deployed to server, i get the Exception as file not found.
String fileToUpload = FlUpldImage.PostedFile.FileName; //#"C:\Users\admin.RSS\Desktop\Photos\me_skype.jpg";
String documentLibraryName = "SiteAssets";
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = web.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = CheckStringNull(txtFirstName.Text) + CheckStringNull(txtLastName.Text) + CheckDateNull(txtDOB) + System.IO.Path.GetFileName(fileToUpload); ;
if (fileName.Contains('/'))
{
fileName = fileName.Replace("/", "");
}
if (fileName.Contains(':'))
{
fileName = fileName.Replace(":", "");
}
FileStream fileStream = File.OpenRead(fileToUpload);
//Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
string url = site.ToString() + "/" + spfile.ToString();
if (url.Contains("="))
{
url = url.Split('=')[1];
}
//Commit
myLibrary.Update();
The string fileupload contains URL as C:\Users\admin.RSS\Desktop\Photos\me.jpg This URL is actually the client system and the server side code throws exception as file not found. How to handle this issue?
UPDATE:
I removed the lines of code that checks if the file exists and now i get the exeption on FileStream fileStream = File.OpenRead(fileToUpload); as c:\windows\system32\inetsrv\20120605_133145.jpg cold not be found
Kindly help. Thank You
if (this.fuAvatarUpload.HasFile && this.fuAvatarUpload.PostedFile.FileName.Length > 0)
{
string extension = Path.GetExtension(file.FileName).ToLower();
string mimetype;
switch (extension)
{
case ".png":
case ".jpg":
case ".gif":
mimetype = file.ContentType;
break;
default:
_model.ShowMessage("We only accept .png, .jpg, and .gif!");
return;
}
if (file.ContentLength / 1000 < 1000)
{
Image image = Image.FromStream(file.InputStream);
Bitmap resized = new Bitmap(image, 150, 150);
byte[] byteArr = new byte[file.InputStream.Length];
using (MemoryStream stream = new MemoryStream())
{
resized.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
byteArr = stream.ToArray();
}
file.InputStream.Read(byteArr, 0, byteArr.Length);
profile.ImageUrl = byteArr;
profile.UseGravatar = false;
profileService.UpdateProfile(profile);
this._model.ShowApprovePanel();
}
else
{
_model.ShowMessage("The file you uploaded is larger than the 1mb limit. Please reduce the size of your file and try again.");
}
}
Saving the file physically onto server and than working on the same helped me resolve my issue.

How to create zip file in asp.net

I need to create zip file from the folder, path:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild\HOST
within that host folder there are 7 txt files.
I want to create zip file HOST.zip in the folder above:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild
I've used Ionic ZIP for this in our own projects.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
public class Ziper
{
public static string MapPathReverse(string fullServerPath)
{
return #"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty);
}
public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
{
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
System.Web.HttpContext c = System.Web.HttpContext.Current;
//String ReadmeText = String.Format("README.TXT\n\nHello!\n\n" +
// "This is text for a readme.");
string archiveName = String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
var path = Server.MapPath(#"../Images/TempFile/TempFile" + DateTime.Now.Ticks);
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
var pathzipfile = Server.MapPath(#"../Images/TempFile/zip_" + DateTime.Now.Ticks + ".zip");
for (int i = 0; i < pathes.Length; i++)
{
if (File.Exists(pathes[i]))
{
string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
File.Copy(pathes[i], dst);
}
}
if (File.Exists(pathzipfile))
File.Delete(pathzipfile);
ZipFile.CreateFromDirectory(path, pathzipfile);
{
byte[] bytes = File.ReadAllBytes(pathzipfile);
Response.OutputStream.Write(bytes, 0, bytes.Length);
}
Response.Close();
File.Delete(pathzipfile);
Directory.Delete(path, true);
}
public Ziper()
{
}
}

load image after upload in asp.net 4.0

My question is image uploading , uploading and image load method are working perfect but im showing images below the upload control, after click upload button new image must be added to line.. what is the reason?
this is uploading code:
DirectoryInfo directoryInfo = new DirectoryInfo(Server.MapPath(#"~/Bailiffs/BailiffImages/"));
string cukurNumber = txtCukurNumber.Text;
int sequence = 0;
string fileName = string.Empty;
FileInfo[] fileInfos = directoryInfo.GetFiles(cukurNumber + "*");
if (afuImage.HasFile)
{
if (fileInfos.Length != 0)
{
for (int i = 0; i < fileInfos.Length; i++)
{
string fileNumber = fileInfos[i].Name.Substring(fileInfos[i].Name.LastIndexOf("-") + 1, fileInfos[i].Name.LastIndexOf(".") - fileInfos[i].Name.LastIndexOf("-") - 1);
sequence = int.Parse(fileNumber) + 1;
}
fileName = cukurNumber + "--" + sequence + ".jpg";
}
else
{
fileName = cukurNumber + "--1.jpg";
}
afuImage.PostedFile.SaveAs(Server.MapPath(#"/Bailiffs/BailiffImages/" + fileName));
CreateImages(); // recreates images
}
thx...
Use ajax to call a page method which retrieves the url of the image just uploaded and shows it in an img tag. Ajax and Jquery are your tools and friends.

Resources