Upload a file using file upload in ASP.net - c#

I wrote the code to upload the file and save in project root directory. How can I change this to save the path into database and the files into a separate folder from project?
protected void UploadButton_Click(object sender, EventArgs e)
{
if(FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch(Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}

protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile) {
try {
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/") + filename);
saveImgPathToDB(filename, 3);
StatusLabel.Text = "Upload status: File uploaded!";
} catch (Exception ex) {
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
private void saveImgPathToDB(string path, int recordID)
{
using (sqlconnection db = new sqlconnection("your_connection_string")) {
using (sqlcommand cmd = new sqlcommand("INSERT INTO photo_table (PhotoPath) VALUES (#path) WHERE someId=#someid", cn)) {
cmd.parameters.addwithvalue("#path", path);
cmd.parameters.addwithvalue("someid", recordID);
cmd.connection.open();
try {
cmd.executenonquery();
}
}
}
}

Related

Unable to evaluate the expression

I'm unable to debug the the SaveFileToDisk method. Please me help me out how to resolve the issue. Thanks in advance.
private void Download_TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
try
{
PortalTeacherDairyAttachmentList attachment = ((TappedEventArgs)e).Parameter as PortalTeacherDairyAttachmentList;
byte[] attachmentbyte = attachment.Attachment;
DependencyService.Get<IDownloadManager>().SaveFileToDisk(attachment.FileName,attachmentbyte);
}
catch (Exception ex)
{
}
}
SaveFileToDiskCode:
{
Toast.MakeText(Android.App.Application.Context, "Downloading started...", ToastLength.Long).Show();
var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads);
var absolutepath = dir.AbsolutePath;
string name = filename;
string filePath = System.IO.Path.Combine(absolutepath, name);
try
{
System.IO.File.WriteAllBytes(filePath, data);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
OpenFile(filePath, filename);
Toast.MakeText(Android.App.Application.Context, "File downloaded at" + filePath, ToastLength.Long).Show();
CreateNotificationChannel(name);
}
catch (System.Exception e)
{
System.Console.WriteLine(e.ToString());
Toast.MakeText(Android.App.Application.Context, "Error occured", ToastLength.Long).Show();
}
}

asp.net FileUploadControl rejects larger files

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string filename = Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(Server.MapPath("~/Files/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
String x = Server.MapPath("~/Files/") + filename;
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
In this simple example, when I try file that is under 1MB, it works well, but if I try 10MB, i get "This site can’t be reached The connection was reset." Which is browser message.
So where's the problem?
Check your web.config file (10mb and 5 minutes):
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="300"/>
</system.web>

BackgroundTransfer cannot move files

I am having problem downloading files using Background transfer. After completion of download when moving file, it gives you an exception Operation not permitted
void addTransferRequest(string fileName)
{
if (string.IsNullOrEmpty(fileName))
return;
string filePathToDownload = string.Empty;
filePathToDownload = activeReciter.DownloadURL;
filePathToDownload += fileName;
Uri transferUri = new Uri(Uri.EscapeUriString(filePathToDownload),
UriKind.RelativeOrAbsolute);
BackgroundTransferRequest transferRequest = new
BackgroundTransferRequest(transferUri);
transferRequest.Method = "GET";
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
Uri downloadUri = new Uri(DataSource.TEMPDOWNLOADLOCATION + fileName,
UriKind.RelativeOrAbsolute);
transferRequest.DownloadLocation = downloadUri;
transferRequest.Tag = fileName;
transferRequest.TransferStatusChanged +=
new EventHandler<BackgroundTransferEventArgs>
(transfer_TransferStatusChanged);
transferRequest.TransferProgressChanged += new
EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
try
{
BackgroundTransferService.Add(transferRequest);
chapterFileNames.Dequeue();
}
catch (InvalidOperationException)
{
}
catch (Exception)
{
}
}
void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
{
ProcessTransfer(e.Request);
}
void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
{
}
private void ProcessTransfer(BackgroundTransferRequest transfer)
{
switch (transfer.TransferStatus)
{
case TransferStatus.Completed:
if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
{
using (IsolatedStorageFile isoStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
string filename = transfer.Tag;
string folderPath = string.Format(#"{0}{1}\{2}\",
DataSource.DOWNLOADLOCATION, activeReciter.ReciterID, chapter.ChapterID);
string fileFullPath = folderPath + filename;
if (!isoStore.DirectoryExists(Path.GetDirectoryName(folderPath)))
isoStore.CreateDirectory(Path.GetDirectoryName(folderPath));
if (isoStore.FileExists(fileFullPath))
isoStore.DeleteFile(fileFullPath);
isoStore.MoveFile(transfer.DownloadLocation.OriginalString, fileFullPath);
//Excpetion is thrown here
RemoveTransferRequest(transfer.RequestId);
}
catch (Exception ex)
{
MessageBox.Show("Error Occured: " + ex.Message + transfer.Tag, "Error",
MessageBoxButton.OK);
return;
}
}
}
break;
}
}
When moving file, it throws exception, I don't know what is wrong with moving (this happens on some of the files not all files).
From the MSDN Page, under File System Restrictions section:
You can create any additional directory structure you choose
underneath the root “/shared/transfers” directory, and you can copy or
move files after the transfer is complete to ensure that the
background transfer service does not modify the files, but attempting
to initiate a transfer using a path outside of the “/shared/transfers”
directory will throw an exception.
Make sure you are not trying to move your file outside from the /Shared/Transfers folder.

How to create a folder then save an image to the created folder using fileuploader in C# asp.net?

I have a simple program here wherein I can create a folder then save the an image to the folder created. The folder gets successfully created but I'm getting error into saving it to the newly created file. The error is:
The file could not be uploaded. The following error occured: 'N:/Kim's New Project/Safety Accident Report/File Uploader 2/File
Uploader 2/Uploads/asdsa' is a physical path, but a virtual path was
expected.
Can you please check my code. Please help. Thank you.
protected void button1_Click(object sender, EventArgs e)
{
if (FileUpload2.HasFile)
{
try
{
if (FileUpload2.PostedFile.ContentType == "image/jpeg")
{
if (FileUpload2.PostedFile.ContentLength < 512000)
{
string strpath = #"N:\Kim's New Project\Safety Accident Report\File Uploader 2\File Uploader 2\Uploads\" + txtName.Text;
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
lblResult.Text = "Directory Created";
if ((Directory.Exists(strpath)))
{
string filename = Path.GetFileName(FileUpload2.FileName);
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
Label1.Text = "File uploaded successfully!";
}
}
else
{
lblResult.Text = "Already Directory Exists with the same name";
}
}
else
Label1.Text = "File maximum size is 500 Kb";
}
else
Label1.Text = "Only JPEG files are accepted!";
}
catch (Exception exc)
{
Label1.Text = "The file could not be uploaded. The following error occured: " + exc.Message;
}
}
Instead of
FileUpload2.SaveAs(Server.MapPath(strpath) + filename);
try
FileUpload2.SaveAs(Path.Combine(strPath, filename));
you already know the physical save path - no need for Server.MapPath
Try..
string strpath = Server.MapPath("~/Test");
if (!(Directory.Exists(strpath)))
{
Directory.CreateDirectory(strpath);
}

How to Transfer Files in different Threads with FileWatcher

I have a form with a File Watcher to which he transfers to multiple addresses all video files placed in a folder. What is the best option so that when multiple files are added to even be able to perform each transfer in a thread. Here's an example of my code:
DockingBarTransferEntities context = new DockingBarTransferEntities();
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
IEnumerable<Diretorios> directories = context.Diretorios.ToList();
foreach (var destino in directories)
{
try
{
Transfere(e.FullPath,Path.GetFileName(e.FullPath),destino);
}
catch (Exception ex)
{
textBox1.Text += "Error: " + ex.Message;
}
}
}
public void Transfere(string fullPath, string name, Diretorios diretorio)
{
try
{
if (Directory.Exists(diretorio.Caminho))
{
string fileName = Path.GetFileName(fullPath);
fileName = String.Format("{0}\\{1}", diretorio.Caminho, fileName);
FileInfo arquivo = new FileInfo(fullPath);
arquivo.CopyTo(fileName, true);
}
}
catch (Exception ex)
{
}
}
It should be as simple as this:
Task.Factory.StartNew(() => Transfere(e.FullPath, Path.GetFileName(e.FullPath), destino));
instead of calling Transfere directly.

Categories