Single File Upload Check in ASP.NET - 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

Related

how to intercept standard output of a dotnetcore process for interactive linux commands

I need to run some interactive commands in dotnet core and interact with the output received. The problem I am encountering is that it doesn't trigger the read error or output events. Here is the example code I am using :
command_process = new Process()
{
StartInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = $"-c \"{escapedArgs}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true,
WorkingDirectory = working_directory,
}
};
command_process.OutputDataReceived += StandardOutputDataHandler;
standard_output = new StringBuilder();
command_process.ErrorDataReceived += ErrorOutputDataHandler;
error_output = new StringBuilder();
command_output = new StringBuilder();
command_process.Start();
command_process.BeginOutputReadLine();
command_process.BeginErrorReadLine();
command_process.WaitForExit();
...
private void StandardOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
Console.WriteLine("StandardOutputDataHandler");
if (String.IsNullOrEmpty(outLine.Data)) return;
Console.WriteLine("After null StandardOutputDataHandler");
lock (command_output)
{
Console.WriteLine("StandardOutputDataHandler output: {0}", outLine.Data);
standard_output.Append(Environment.NewLine + " " + outLine.Data);
command_output.Append(Environment.NewLine + " " + outLine.Data);
has_standard_output = true;
ParseOutput();
}
Console.WriteLine("End StandardOutputDataHandler");
}
private void ErrorOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
Console.WriteLine("ErrorOutputDataHandler");
if (String.IsNullOrEmpty(outLine.Data)) return;
Console.WriteLine("After null ErrorOutputDataHandler");
lock (command_output)
{
Console.WriteLine("ErrorOutputDataHandler output: {0}", outLine.Data);
error_output.Append(Environment.NewLine + " " + outLine.Data);
command_output.Append(Environment.NewLine + " " + outLine.Data);
has_error_output = true;
ParseOutput();
}
Console.WriteLine("End ErrorOutputDataHandler");
}
This happens for any interactive commands such as (replace escapedArgs with any of the following) :
mysql -u root -p
ftp x.x.x.x
When it starts running, it ouputs the console:
Enter password:
in the case of the mysql command which seems to me it sent the output before the Process has attached the output buffer, not sure if that's the best interpretation. And it enters the StandardOutputDataHandler or ErrorOutputDataHandler only after a few seconds, with empty data and then the Process closes as well.
Not sure how to work around the issue or what the explanation for how it happens is.
Thanks

Cannot upload files from android to asp.net server using Cordova FileTransfer plugin

I have a simple mobile app created using cordova file transfer plugin. Below is the upload code
function uploadPhoto(fileURI) {
var options = new FileUploadOptions();
options.fileKey = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
if (cordova.platformId == "android") {
options.fileName += ".jpg"
}
options.mimeType = "image/jpeg";
//options.contentType = 'multipart/form-data';
options.params = {}; // if we need to send parameters to the server request
options.headers = {
Connection: "Close"
};
//options.httpMethod = 'POST';
//options.chunkedMode = false;
var ft = new FileTransfer();
rst.innerHTML = "Upload in progress...";
ft.upload(
fileURI,
encodeURI("http://localhost:55013/virtualroomservice.asmx/SaveImage"),
onFileUploadSuccess,
onFileTransferFail,
options, true);
function onFileUploadSuccess (result) {
// rst.innerHTML = "Upload successful";
console.log("FileTransfer.upload");
console.log("Code = " + result.responseCode);
console.log("Response = " + result.response);
console.log("Sent = " + result.bytesSent);
console.log("Link to uploaded file: https://www.kinrep.com/foster/ws/contentlibrary" + result.response);
var response = result.response;
var destination = "https://www.kinrep.com/foster/WS/ContentLibrary" + response.substr(response.lastIndexOf('=') + 1);
if(this.id == 'uploadcheque') {
document.getElementById("hdnchequeimgpath").value = destination;
} else if(this.id == 'uploaddoorlock') {
document.getElementById("hdndoorlockedimgpath").value = destination;
} else {
document.getElementById("hdnothersimgpath").value = destination;
}
rst.innerHTML = "File uploaded to: " +
destination +
"</br><button class=\"button\" onclick=\"window.open('" + destination + "', '_blank', 'location=yes')\">Open Location</button>";
//document.getElementById("downloadedImage").style.display="none";
}
function onFileTransferFail (error) {
rst.innerHTML = "File Transfer failed: " + error.code;
console.log("FileTransfer Error:");
console.log("Code: " + error.code);
console.log("Source: " + error.source);
console.log("Target: " + error.target);
}
}
Below is the server code
[WebMethod]
[ScriptMethod]
public string SaveImage()
{
try
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
if (file == null)
return "0";
string targetFilePath = Server.MapPath(#"WS\ContentLibrary") + file.FileName;
file.SaveAs(targetFilePath);
}
catch (Exception ex)
{
string s = ex.Message;
return s;
}
return "1";
}
When the call gets invoked it is getting inside SaveImage webmethod but HttpContext.Current.Request.Files.Count is 0. The same call when I point to filedropper.com as given in example code it worked fine (i could see the uploaded image on filedrop.com) but not working when pointing to my windows web service. I have seen various other posts but could not just figure out whats going wrong. In the client console it writes no of bytes sent which means there is no issue from client side where as server side there seems to be an issue. Can anyone suggest where the issue is?
Below is the debug output
UPDATE-06112016-5:35PMIS
Still clueless also posted in http://www.telerik.com/forums/file-upload-not-working-93d711a97c9b
UPDATE-06112016-9-54PMIS
After a nightmare not been able to figure out how to fix the issue I decided to go with hosting a php on iis as alternative. Cordova File Transfer plugin seems to work fine with php server page as here
Apparently, IIS 7.5 in fast CGI mode has a bug regarding chunked multipart form data: https://bugs.php.net/bug.php?id=60826
The FileTransfer plugin for Cordova defaults the chunked mode to true:
chunkedMode: Whether to upload the data in chunked streaming mode. Defaults to true. (Boolean)
In my case this was exactly the problem and setting options.chunkedMode to true fixed it right away.
Note that you won't be able to use the onprogress property anymore.
onprogress: Called with a ProgressEvent whenever a new chunk of data is transferred. (Function)

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.

Failed to upload image saved on server

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();
}
}

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