Failed to upload image saved on server - asp.net

I am saving an image file at server. The file is successfully saved at the server but when I try to assign the URL of that file to the image control, the image is failed to load but when I assign that url directly in to HTML code, the file is loaded successfully. Please guide me Where I am making a mistake. Below are the code for my file upload and fetch URL.
Code For File Upload
private string ImageUpload()
{
try
{
string FileName = UpldCompanyLogo.FileName;
if (UpldCompanyLogo.HasFile)
{
string SaveFilePath = Server.MapPath("~\\Upload\\")+FileName;
if (!Directory.Exists(Server.MapPath("~\\Upload\\")))
Directory.CreateDirectory(Server.MapPath("~\\Upload\\"));
if (File.Exists(SaveFilePath))
{
File.Delete(SaveFilePath);
}
if(File.Exists(ViewState["ImageURL"].ToString()))
{
File.Delete(ViewState["ImageURL"].ToString());
}
UpldCompanyLogo.PostedFile.SaveAs(SaveFilePath);
}
return FileName;
}
catch (Exception ex)
{
if (ex.HelpLink == null)
ex.HelpLink = "Controls_Company103>>" + ex.Message;
else
ex.HelpLink = "Controls_Company103>>" + ex.HelpLink;
lblMessage.Text = ex.HelpLink;
lblMessage.CssClass = "ERROR";
return null;
}
}
This is the code to get the image URL
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
string path = Server.MapPath("~\\Upload\\");
imgLogo.ImageUrl = path + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}
If I copy and past the retrieved path in the browser, the image is found there at the server.

You may try this:
if (dtCompany != null)
{
if (dtCompany.Rows.Count > 0)
{
txtCompanyName.Text = dtCompany.Rows[0]["CompanyName"].ToString();
txtAddress.Text = dtCompany.Rows[0]["Address"].ToString();
txtPhoneNo.Text = dtCompany.Rows[0]["PhoneNumber"].ToString();
txtFaxNo.Text = dtCompany.Rows[0]["FaxNumber"].ToString();
imgLogo.ImageUrl = Page.ResolveUrl("~\\Upload\\") + dtCompany.Rows[0]["CompanyLogo"].ToString();
}
}

Related

Xamarin.Forms failing to use EvoHtmlToPdfclient in order to convert html string to a pdf file

I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.

Cannot find part of path while uploading image to a folder in Asp.net

I am uploading a profile picture of a user to a folder and saving its path to RavenDB. But my code is giving me an error that part of path is not found. On this line
file.SaveAs(path);
Code:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType);
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
You have a typing error in your path...
Replace...
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
With...
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), FileName);
You also need to make sure you have the relevant permissions to write to this directory.
Based on your error, the filepath looks incorrect.
c:\users\wasfa\documents\visual studio
2012\Projects\MvcMembership\MvcMembership\App_Data\Uploads\daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg
is daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg the name of the file?
Try:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
Before file.SaveAs(path), try to check directory exist, if not, create one,
if(CreateFolderIfNeeded(path);
{
file.SaveAs(path);
}
A private function to create directory if needed,
private static bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{ result = false; }
}
return result;
Hope this helps.
Check the var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType); line in your code.
The file.ContentType will not return the extension of the file you are uploading. It shuold be like daed3def-df2b-4406-aa‌​9e-c1995190aa6d.jpeg instead of daed3def-df2b-4406-aa‌​9e-c1995190aa6d.image\jpeg
find the extension from the uploaded file using substring.
Hope this help

Single File Upload Check in ASP.NET

Following code transfer file successfully, but does not print in lable that it has been transferred. Although other checks were shown perfectly. Is there any logical eror in it?
if (txtFile1.HasFile)
{
var folderfile1 = Server.MapPath("~/files/Operations_Support/IMSI");
string flFile1 = txtFile1.PostedFile.FileName;
string saveflFile1 = folderfile1 + "\\" + System.IO.Path.GetFileName(flFile1);
FileInfo Finfo = new FileInfo(txtFile1.PostedFile.FileName);
if (Finfo.Extension.ToLower() == ".txt")
{
if (txtFile1.PostedFile.ContentLength < 1024)
{
//if (!File.Exists(folderfile1))
if (Directory.GetFiles(folderfile1).Length == 0)
{
txtFile1.SaveAs(saveflFile1);
//lbFile1.Visible = true;
lbFile1.Text = "Upload status: IMSI file transfered successfully";
}
else
{
lbFile1.Text = "Upload status: Please wait until the previous file is processed";
}
}
else
lbFile1.Text = "Upload status: The file has to be less than 1 kb!";
}
else
lbFile1.Text = "Upload status: Only Text files are accepted!";
}
else
{
lbFile1.Visible = true;
lbFile1.Text = "Upload status: Please select file";
}
Use File.Exists like this:
var folderfile4 = Server.MapPath("~/files/Path");
string saveflFile4 = folderfile4 + "\\" + System.IO.Path.GetFileName(flFile4);
if(!File.Exists(saveflFile4))
txtFile4.SaveAs(saveflFile4);
else
txtError.Text = "File exists";
Server.MapPath returns a physical path on the server, so you can use File.Exists to check if the file is present or not.
use the File.Exists method
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx

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.

Problem uploading Excel-document. What's wrong?

For some reason, not all of Excel-documents can be upload from my computer. In half the cases get the error ".. no!! error:" from a block of try-catch .. What is wrong?
private function importXLS(e:MouseEvent):void {
fr = new FileReference();
var fileFilter:FileFilter = new FileFilter("Excel (.xls)", "*.xls");
fr.addEventListener(Event.SELECT,selectXLS);
fr.browse([fileFilter]);
statusLabel.text = "selecting...";
}
private function selectXLS(e:Event):void {
fr = FileReference(e.target);
fr.addEventListener(Event.COMPLETE, fileIn);
fr.load();
statusLabel.text = "loading...";
}
private function fileIn(e:Event):void {
ba = new ByteArray();
ba = fr.data;
xls = new ExcelFile();
var flag:Boolean = false;
try{
xls.loadFromByteArray(ba);
flag = true;
}catch(error:Error){
Alert.show("no!! error: " + error.getStackTrace());
}
if (flag == true) {
statusLabel.text = "XlS loaded.";
} else {
statusLabel.text = "XlS didn't load.";
}
}
You are reading the entire file into memory. If a user tries to upload too big a file, their browser will crash. Is there a reason you doing this? Are you using the bytes in the client or just passing them to the server. If you are passing them to the server, you want to just not use the fr.load method that you call in selectXLS(). Instead use fr.upload and avoid your whole problem.

Resources