I tried to update file to physically via my controller. But my controller save in local (actually Visual Studio run) perfectly but when I tried to publish and setup to on my server and use www.mywebsite.com then controller couldn't save to path without an error.
My scenerio is like this:
In client side onReady js method, I get physical root path from my database (this is work both side, no problem i watching debug console). My physical path like this: \\192.168.1.1\MYFILE-1.1
I pass to value with POST method file and root path via Model
In a controller side, I create timestamp for a file name, and combine more path file. Like this my controller:
[HttpPost]
public JsonResult SavePhysicalPath(FileModel model)
{
//create timestamp of file name
string filesMimeType = MimeTypesMap.GetMimeType(model.FormFile.FileName);
string filesExtType = MimeTypesMap.GetExtension(filesMimeType);
string fnTimeStamp = DateTime.Now.ToString("ddMMyyyy_HHmmssffff");
string edittedFileName = fnTimeStamp + "." + filesExtType;
string edittedFmAndSubPath = "MyDocs\\OtherFiles\\" +edittedFileName ;
var savingRootPath = "";
savingRootPath =model.FileFolderPath; // FileFolderPath is string get from view "\\192.168.1.1\MYFILE-1.1"
try
{
string SavePath = Path.Combine(Directory.GetCurrentDirectory(), savingRootPath, edittedFmAndSubPath );
using (var stream = new FileStream(SavePath, FileMode.Create))
{
model.FormFile.CopyTo(stream);
}
stringOutput = "OK";
return Json(stringOutput);
}
catch (Exception ex)
{
stringOutput = "ERR";
return Json(stringOutput);
throw;
}
}
if there is no directory, then create one.
bool exists = System.IO.Directory.Exists(SavePath);
if (!exists)
System.IO.Directory.CreateDirectory(SavePath);
or you can create one in manually on server.
Related
I'm trying to copy my database file from the isolated storage to the Download folder (or any folder that the user can access).
Currently my database is stored in:
/data/user/0/com.companyname.appname/files/Databases/MyDatabase.db
I tried to use this code:
public string GetCustomFilePath(string folder, string filename)
{
var docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var libFolder = Path.Combine(docFolder, folder);
if (!Directory.Exists(libFolder))
Directory.CreateDirectory(libFolder);
return Path.Combine(libFolder, filename);
}
var bas = GetDatabaseFilePath("MyDatabase.db");
var des = Path.Combine(Android.OS.Environment.DirectoryDownloads, "MyDatabase.db");
File.Copy(bas, des);
The Android.OS.Environment.DirectoryDownloads property returns the path Download, which is the name of the downloads folder.
But File.Copy() throws an exception telling
System.IO.DirectoryNotFoundException: Destination directory not found:
Download.
I tried to use a slash before like this: /Download/MyDatabase.db with no luck.
Is there any way to copy a file like that? Do I need any permission?
1st) Yes, you do need permissions to write to external storage.
You can get the runtime time permission required by doing it yourself:
https://devblogs.microsoft.com/xamarin/requesting-runtime-permissions-in-android-marshmallow/
Or via a 3rd-party plugin, such as James Montemagno's PermissionsPlugin
https://github.com/jamesmontemagno/PermissionsPlugin
2nd) Once your user accepts that it is ok to write to external storage, you can use:
Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads
To obtain the path of the device's public Download folder, i.e. using a Forms' dependency service:
public interface IDownloadPath
{
string Get();
}
public class DownloadPath_Android : IDownloadPath
{
public string Get()
{
return Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
}
}
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/dependency-service/introduction
You end up with something like:
public void Handle_Button(object sender, System.EventArgs e)
{
var fileName = "someFile.txt";
using (var stream = File.Create(Path.Combine(FileSystem.CacheDirectory, fileName)))
{
// just creating a dummy file to copy (in the cache dir using Xamarin.Essentials
}
var downloadPath = DependencyService.Get<IDownloadPath>().Get();
File.Copy(Path.Combine(FileSystem.CacheDirectory, fileName), downloadPath);
}
I am trying display images on the webpage from the folder placed in my project root directory. The path that I am storing in the database is as follows:
D:\Projects\OnlineStore\OnlineStore\OnlineStore\Content\Uploads\Images\Bundles\706976d31e274e7ab36986b9bec2f0f9-Object
Image.jpg
The code that generated this path is as follows:
var path = Path.Combine(Server.MapPath("~/Content/Uploads/Images/Bundles"), fileId);
photo.SaveAs(path);
Image doesn't show using this path. The path that works is as follows:
\Content\Uploads\Images\Bundles\706976d31e274e7ab36986b9bec2f0f9-Object
Image.jpg
How do I resolve this issue? I was thinking about using first path to save image file to folder and save second path in the database. But this doesn't seem the right way of doing this.
1. Only store FileName in database Check this.
string fileName = System.IO.Path.GetFileName(file.FileName);
//store fileName in your ImageName column of Image your Image table
//Note: generate unique filename using `Guid` or `PrimaryKey` to overcome
//same file name issue.
2. Use #Url.Content to show image in view.
<img src="#Url.Content("~")/Content/Uploads/Images/Bundles/#Model.ImageName"/>
Reference
In controller:
public ActionResult UserRegister(Register Register)
{
try
{
DbConnection dbHandle = new DbConnection();
dbHandle.Connection();
using (SqlCommand UserRegistercmd = new SqlCommand("USPUserRegistration", dbHandle.con))
{
DateTime dob = Convert.ToDateTime(Register.dateOfBirth);
string Random = System.DateTime.Now.ToString("ddMMyyhhmmss");
Register.UserPhoto = "../Images/" + Random + Register.userImg.FileName;
Register.userImg.SaveAs(Server.MapPath("../Images/") + Random + Register.userImg.FileName);
UserRegistercmd.CommandType = CommandType.StoredProcedure;
dbHandle.con.Open();
UserRegistercmd.ExecuteNonQuery();
dbHandle.con.Close();
ViewBag.error = "Company Registration Sucess";
Mail.SendMail(Register.email,"Your User Name and Password ","User Name :"+Register.username+"Paassword :"+Register.password);
}
}
catch (Exception e)
{
ViewBag.error = "Error!!";
ExceptionLog.Log(e, Request.UserHostAddress);
return RedirectToAction("Error_View", "CompanyRegister");
}
finally
{
Dispose();
}
return RedirectToAction();
}
in cshtml use #Url.Content:
<img src="#Url.Content(#Model.UserPhoto)" alt="There is no Image" style="height:150px;width:150px" onclick="ChangeImg()" />
I'm using Linq to Excel library for reading excel tables. Until now, it was working good locally, the method ExcelQueryFactory gets the route of the excel by this way:
var book = new ExcelQueryFactory(#"C:\data.xls");
Now, I would like to use it online on a Rest Api, the POST used for uploading the Excel to the web api is the following:
[HttpPost]
[Route("Upload")]
public Task<HttpResponseMessage> UploadFile() {
List<string> savedFilePath = new List<string>();
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
var provider = new MultipartFileStreamProvider(rootPath);
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsCanceled || t.IsFaulted)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
foreach (MultipartFileData item in provider.FileData)
{
try
{
string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
string newFileName = Guid.NewGuid() + Path.GetExtension(name);
Debug.WriteLine(item.LocalFileName);
File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
//RELATIVE PATH
string fileRelativePath = "~/UploadedFiles/" + newFileName;
//LeerExcel(fileRelativePath);
//ABSOLUTE PATH
Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
savedFilePath.Add(fileFullPath.ToString());
//LeerExcel(savedFilePath[0]);
}
catch (Exception ex)
{
string message = ex.Message;
}
}
// string rutaFin = "~" + savedFilePath[0];
// string rest = rutaFin.Replace("http://localhost:56618", "");
// LeerExcel(rest);
return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
});
return task;
}
So, by choosing the excel manually, neither the absolute path or relative path on the server work for the ExcelQueryFactory string route.
The routes get by this method are the following:
ABSOLUTE:
http://localhost:56618/UploadedFiles/9a27e785-e486-4807-8a80-7abb9b940d8b.xls
And the relative:
/UploadedFiles/9a27e785-e486-4807-8a80-7abb9b940d8b.xls
Is possible to use by the way I want to? During the server is online, the obtained absolute path is accesible, so if I access to that URL, the file is downloaded.
the problem is solved:
As I said, I thought only this library worked locally, but it wasn't.
Since Microsoft has launched a new big update, many people have notice some problems when using Database engine, “Unexpected error from external database driver (1). (Microsoft JET Database Engine)” after applying October security updates.
First, I created a Fake.txt file on /UploadedFiles, folder that is located on the project repository and I give it permission to be always copied, as follows:
Fake.txt properties
With this file, I´m achieving that UploadedFiles folder is copied every time I run the server.
Next step:
Due to Microsoft big update, the recomendation is to "download and install the Microsoft Access Database Engine 2010 Redistributable, and then modify the DB connection strings in Microsoft Excel to use ACE as a provider. Example: Change Provider=Microsoft.Jet.OLEDB.4.0 to Provider=Microsoft.ACE.OLEDB.12.0."
I only have downloaded and install that file, but during this day, 3 new windows updates were installed, so, I dont know if this 3 updates are related with the solution of this problem.
The updates are:
Update 1
Update 2
Update 3
After installing the 2010 database engine version file, I changed the excel extension from .xls to .xlsx and now all work.
I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when Directory.CreateDirectory(savePath); Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks
Here is My Method:
protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
{
if (e.IsValid)
{
String savepath = String.Format("{0}{1}\\", MapPath(#"~\TicketUploads\"), Session["lastcallid"]);
if (!Directory.Exists(savepath))
{
Directory.CreateDirectory(savepath);
}
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
e.UploadedFile.SaveAs(savefile);
String urlPath = String.Format("{0}{1}\\{2}", #"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
fltdet.hasattachment = "Y";
fltdet.AttachUrl = urlPath;
fltdet.Save();
}
}
For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use: "{0}{1}\\"
please try this
string sessionVariable = Convert.ToString(Session["lastcallid"]);
string path = Path.Combine(MapPath(#"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Also
I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.
I am using the following code to save my file into database using entity framework But for some reason it is giving me the error:
'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 'C:/Users/David Buckley/Documents/Visual Studio 2012/Sis/StudentInformationSystem/admin/uploads/' is a physical path, but a virtual path was expected
But it seems to save the file ok in database as the path and filename of C:\Users\David Buckley\Documents\Visual Studio 2012\Sis\StudentInformationSystem\admin\uploads\test.jpg which exsits but i persume I need to save it differently if I want to load it into an image control imageurl field property?.
try
{
int id = Convert.ToInt32(Request.QueryString["id"]);
if (id == -1) // we neeed a new record otherwise get the old one;
{
Student studentRecord = new Student();
_db.AddStudent(studentRecord);
_db.SaveChanges();
newRecordId = studentRecord.Student_ID;
Session["recordid"] = id;
_student = _db.GetStudentById(newRecordId);
}else
_student = _db.GetStudentById(id);
photoUpload.TargetFolder= Server.MapPath("~/admin/uploads/");
string fullPath = Server.MapPath( "~/admin/uploads/");
photoUpload.OverwriteExistingFiles = true;
string newFileName = "";
foreach (UploadedFile file in photoUpload.UploadedFiles)
{
string fileName = "test";
newFileName =fileName + file.GetExtension();
file.SaveAs(Path.Combine(fullPath, newFileName));
// impelement your database insert here...
}
string thumbPath;
thumbPath = ("~/images" + "/" + newFileName);
_student.Image = thumbPath;
_student.Student_Name = txtStudentName.Text;
_student.Student_FatherName = txtFathersName.Text;
_student.Registration_no = txtRegistrationNo.Text;
_student.Address1 = txtAddress1.Text.Trim();
_student.Address2 = txtAddress2.Text.Trim();
_student.Address3 = txtAddress3.Text.Trim();
_student.RelationWithGuadian = txtRelationshipGurdan.Text.Trim();
_student.GurdianName = txtGurdianName.Text.Trim();
_student.LastSchoolAtten = txtLastSchool.Text.Trim();
_student.Contact1 = txtContact1.Text.Trim();
_student.Contact2 = txtContact2.Text.Trim();
_student.DOB = rdDOB.SelectedDate.Value;
_db.SaveChanges();
}
catch (Exception ex)
{
}
To access the file from a web application, you will need to use a virtual path. But you are saving a physical path to the file in the database. Instead of saving the value of Path.Combine(fullPath, newFileName) in the database, you should be saving the value of "~/admin/uploads/" + newFileName.
The above works as long as your uploads/ directory is a descendant of your application directory. Alternatively, you can use a path that points to a directory outside of your application path by explicitly adding a virtual directory.
How to add a virtual directory in IIS express
How to add a virtual directory in IIS