How to get the uploaded file path? - asp.net

I am using input tag type="file" to browse the file in asp.net.
I browsed the file "Linq2sql.zip" from the location "c\Desktop\Karthik\Linq2sql.zip".
i can get the file name and path using
HttpPostedFileBase file;
var filePath = Path.GetFullPath(file.FileName);
But File path is like = C:\\Program Files (x86)\\Common Files\\Microsoft Shared\\DevServer\\10.0\\Linq2sql.zip
i have to get the original file path c\\Desktop\\Karthik\\Linq2sql.zip. How can i get?

You can not get the original path of the file on the client system; that information is not sent by the client.
The reason you get what you do with GetFullPath is because that forces a resolution with the simple file name alone with the current directory of the asp.net process. That info is utterly meaningless - and in fact incorrect - in this case.

Related

what is absolute path in C++/WinRT

the error: WinRT originate error-0x80070057:'The specified path (msappx:\Local\C:\Windows\Web\Screen\img103.png) is not an absolute path, and relative paths are not allowed. '
when I used C++/WinRT,the function call is
winrt::Windows::Foundation::IAsyncOperationwinrt::Windows::Storage::StorageFile temp = StorageFile::GetFileFromPathAsync(hFilname);
what can I do?
For StorageFile.GetFileFromPathAsync() method, you don't have permission to access the specified file, please see here.
My suggestion is that you could store the image file in Application install directory that app can access, then use the following code to access it.
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
string path= Path.Combine(folder.Path, #"Data\img1.png");
StorageFile.GetFileFromPathAsync(path);
Note that the Application install directory is ..ProjectPath\bin\x86\Debug\Appx

absolute File path to relative file path

I have a class library project (D:/projectName/SampleClassPrj) and a console application project D:/projectName/ConsolePrj.
In class library project, a json file test.json and a class sample.cs (read and deserialise json) both present.
d:/projectName/SampleClassPrj/test.json
d:/projectName/SampleClassPrj/sample.cs
This works with absolute path like,
d:/projectName/SampleClassPrj/test.json
but not working with relative path.
with relative path, by using file not found error as it is trying to find the file in the console (running) application assembly folder.
D:/projectName/ConsolePrj/bin/test.json
please help to find the solution
first, check json file property "copy if newer".
then, use Appdomain.CurrentDomain.BaseDirectory
string result = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ConnectionString.txt"));
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location.Substring(0, Assembly.GetEntryAssembly().Location.IndexOf("bin\")));
StreamReader r = new StreamReader(Path.Combine(path, "sample.json"))
for .NET core 3.1
This worked for me

CSV to Neo4j-Graph

I'm trying to convert database(csv files) to neo4j-graph, but I get an error.
The command is
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///Users/PERC/AppData/Roaming/Neo4j%20Desktop/Application/neo4jDatabases/database-37b84fcf-d1b2-4dee-a4ee-5faed9cbaca0/installation-3.3.1/import/customers.csv" AS row
CREATE (:Customer {companyName: row.CompanyName, customerID: row.CustomerID, fax: row.Fax, phone: row.Phone});`
The customers.csv file in on import folder of Neo4j Desktop folder. But I get this error:
Couldn't load the external resource at: file:/C:/Users/PERC/AppData/Roaming/Neo4j%20Desktop/Application/neo4jDatabases/database-37b84fcf-d1b2-4dee-a4ee-5faed9cbaca0/installation-3.3.1/import/Users/PERC/AppData/Roaming/Neo4j%20Desktop/Application/neo4jDatabases/database-37b84fcf-d1b2-4dee-a4ee-5faed9cbaca0/installation-3.3.1/import/customers.csv
If you take a look at your error message, you will see that the actually-used file URL repeats the file path.
As stated in the dev manual:
File URLs will be resolved relative to the dbms.directories.import
directory. For example, a file URL will typically look like file:///myfile.csv or file:///myproject/myfile.csv.
Since your CSV file is directly in your import directory, try this:
USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:///customers.csv" AS row
CREATE (:Customer {companyName: row.CompanyName, customerID: row.CustomerID, fax: row.Fax, phone: row.Phone});

Pyexcel, loading a file to create a book in memory

This is solved; thanks to #vmontco's solution: I was missing MEDIA_URL, now it works perfectly.
----------original question below-----------
I welcome suggestions from every angle; I am fairly new to Django and Python. I'm sure I am missing something simple.
Using a Model Form, with a FileField, I upload and save an Excel file to a folder structure under MEDIA_ROOT. This works.
I want to read that same file later to perform operations using Pyexcel. This is where I am stuck. I am attempting to upload the file using the FileField stored in the DB.
This is where I have problems, and I am not sure if am misunderstanding MEDIA_ROOT, or some other aspect of Django.
When I pass the pk to the 2nd view, I then instantiate an object based on the Model. It has the FileField 'docfile', which I am trying to use to access the file to do some operations using Pyexcel,
here is the FileField declaration from models.py:
docfile = models.FileField(
verbose_name="Choose file to upload:",
upload_to='Excel_CSV_Assets/%Y/%m/%d')
EDIT: If I hard-code the pth to the file like this, everything works, including operations afterwards:
thedocfile='site_static/site/original_assets/Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
book=pyexcel.get_book(file_name=thedocfile)
:END OF EDIT
Here is the code from the 2nd view, where I attempt to read the file into memory, and make a 'book' class object using Pyexcel. I am stuck here:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=asset.docfile)
Here is my error description:
Here is the info right at where my code breaks:
Although it says "Wrong filename", I can see the file is in the folder:
I'm able to open the file by double-clicking; the file is not corrupted.
EDIT:
If I cast the 'asset.docfile' to str, like so:
asset = Excel_CSV_Asset.objects.get(id=assetid)
book=pyexcel.get_book(file_name=str(asset.docfile))
I get a different error:
[Errno 2] No such file or directory: 'Excel_CSV_Assets/2016/04/23/Animals_oglc4DV.xlsx'
...but this is the correct directory, located beneath the MEDIA_ROOT file structure.
Here is settings.py MEDIA_ROOT:
MEDIA_ROOT = 'site_static/site/original_assets/'
Here is urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^e/', include('excel_to_mongo.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Here is the url.py of that app:
url(r'^efactory/(?P<assetid>\d+)/$', 'display_sheet_column_choices', {}),
I think your problem is that you don't fully understand the media files management with Django.
What are media files?
Media files are all the files that are user-uploaded (at running time).
You must not mistake them with Static files that are assets needed by your project to work and that you add at development time (CSS, background picture and JS files for instance).
You shouldn't mix them because they are managed differently by the server and that it could lead to security problems (cf. the warning here):
Static files management :
You put your static files as a part of the code either in one static subdirectory from the installed django applications, either in one of the locations you added to STATICFILES_DIRS.
Static files have to be gathered before starting the server by calling ./manage.py collectstatic, this command will collect (copy) the static files into the a directory (STATIC_ROOT's value).
You then have to set STATIC_URL to choose with wich url you should serve your static files. An usual choice would be /static/. To access the static file you should then try to reach /static/path/to/static/file/in/static_root/dir.
Media files management :
Your media files are added at running time. They are stored in the MEDIA_ROOT location that has to be an absolute path. Hence the fact I suggested you to join the BASE_DIR value (an absolute path) and the subdir you would choose with something like :
MEDIA_ROOT = os.path.join(BASE_DIR, "/media/subdir")
You then have to set an URL for your media files, by using the MEDIA_URL variable. To access your media files, the urls will start with the value you choose :
MEDIA_URL = '/media/'
Then, add this to your urls.py file :
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
With the current example, your mymediafile.txt will be located at /path/to/your/project/media/subdir/path/in/media/root/mymediafile.txt and served at http://127.0.0.1:8000/media/path/in/media/root/mymediafile.txt.
But this is suitable only for a development use as told here. And this would work only for DEBUG == TRUE
For a production use, you should consider deploying your media files with your http server (apache for instance).
Conclusion :
Take the time to understand this. Because I suspect you don't really understood what you did and this lack of understanding could lead to future bugs and errors.

Can't Delete file with File.Delete(path)

I'm unable to delete file with this command ..
Exception Details: System.IO.DirectoryNotFoundException: Could not find a part of the path
Im getting the above error ..
However Im able to download file with the very same path..
Additional Details: I've have File path saved in the DataBase..
and files are in the ~\Upload\ folder ..
Path like this "~\Upload\ folder" are virtual paths. You need to convert them to physical path to delete them.
If you are in web context then use the following code to get physical path and then delete them.
var physicalPath = HttpContext.Current.Server.MapPath("~/Upload/folder/file.html"); //to get the physical path
File.Delete(physicalPath);
Ensure that you are escaping any backslashes/forward, and just generally check that your path is complete with no small errors.
Failing that make sure your program has the correct privileges to delete the file.
Sorry I can't be more specific but you have not shown your code.

Resources