Uploading files to Web Application in a sub-dirctory using ASP.NET MVC - asp.net-mvc

I made an ASP.NET MVC web application that is existed in a Sub-Directory. The problem is every time I try to upload file I get this error "Could not find a part of the path".
The code is working perfectly on my local machine and other web apps, so I think the problem is related to the web app being exist in the sub-directory, but I don't know how to solve it.
Thanks in advance.
This is my function
public byte newImage(HttpPostedFileBase newFile, string uploadPath)
{
if (newFile != null && newFile.ContentLength > 0)
{
if (newFile.ContentLength > 3000000) //means file size maximum is 3 MB
return 1; //means the file size is more than 3 MB
var fileName = Path.GetFileName(newFile.FileName);
var path = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(uploadPath), fileName);
newFile.SaveAs(path);
return 0; //means file uploaded successfuly
}
return 2; //means no file was chosen
}//Upload New Image

Did you "map" the upload folder properly? You can read more here.
DirectoryInfo yourUploadDir = new DirectoryInfo(HostingEnvironment.MapPath("~/YourUploadFolder"));

I figured out what's wrong. It seems I forgot to add ~ -_-
So if anyone faced this error, first check if you forgot to add ~. I suppose it worked well on my local machine and other web apps because they were on the root, but once it's placed on a sub-directory, We need to use relative path using this tilde ~.

Related

cordova-plugin-file: files not accessible after app update (iOS)

I am experiencing a funny problem: I am developing an ionic app, using cordova-plugin-file to store images. The resulting paths (URIs in form file:///...) are stored in a SQLite DB along with more information. When I install the app and use it, all works perfect. But if I update (or reinstall) the app, the old images are not found anymore, while newly added images work perfect.
I first suspected that the image files were being deleted on update, but I checked the content of the directory and the files are still there. (FYI: I am using file.dataDirectory/scans/ to place my files).
Then I thought that maybe I could go around the problem loading into img src a base64 blob loaded with cordova.file.readAsUrl(), but cordova.file does not find the file as well (I insist, the files are there, I checked with XCode).
So I checked further with cordova.file and it only finds files that are added after last app install, but the older files are still present in the directory.
Here my code:
private getImgSrcFromDocument(doc: Document): any {
const uri = doc.fileName;
const src = this.webView.convertFileSrc(uri);
const sanitized = this.sanitizer.bypassSecurityTrustUrl(src);
console.log({uri, src, sanitized});
return sanitized;
}
<img class="document_thumbnail" [src]="getImgSrcFromDocument(doc)">
I have already checked this, but is not my case.
By the way, the same code works perfect on Android.
Any idea what could be the problem?
Thanks in advance!
I found the reason why and the solution (very obvious when you know the problem):
Reason
On every new install, iOS renames the data directory for the app. The directory path has this form:
file:///var/mobile/Containers/Data/Application/ABC0000-1234-99DD-00FA-E835FEA/Library/NoCloud/
The hash in the middle is renewed on every install, so the stored full paths in DB are not valid anymore.
Solution
If you still can do it (no deploy yet, no real users), store only the relative path and complete it every time with this.file.dataDirectory (or wherever you wanted to store your files).
If you already have real users and want your update to 'find the files', just ignore the first part of the stored path and build it like before:
const ValidUri = this.file.dataDirectory + // The injected cordova-plugin-file
'relativeSubDirectories/' + // If you store your files in some subdirectory
this.document.storedFullPath.substr( // Take from fullPath only the filename
this.document.storedFullPath.lastIndexOf('/') + 1
);
Where storedFullPath is the string file:///var/mobile/....
After that, you still have to do the webView conversion and the sanitizing, like in the question above.
Hope this helps someone.

IIS 7.5 issue on reading large CSV files

I have an MVC 4 application that currently reads data from a CSV file (this is based on client requirements, even if I wanted to have a database for it). All is working well when I debug and run it from visual studio. However, when I deploy it on IIS 7.5, it is unable to read large CSV files (currently, the largest i have is around 6000kb). I tried different techniques on reading the files, but it just produces the same result. But small files are being read perfectly.
Here is my code in parsing the file:
using (CsvReader csv =
new CsvReader(new StreamReader(_filePath), false, ';'))
{
while (csv.ReadNextRecord())
{
int fieldCount = csv.FieldCount;
string currentRow = "";
for (int i = 0; i < fieldCount; i++)
{
currentRow += csv[i] + ";";
}
this.AddKYCFolder(this.CreateKYCFolder(currentRow.Split(';')));
}
}
Any ideas on this?
Many thanks!
Thank you for taking time to look into my question. Apparently, there were some methods that uses parallelism (Parallel.For) that is, I suppose, not compatible with my IIS setup. The log4net error logging greatly helped me to find the source of error.

Multiple input file tags with IOS 6+ on iPad/iPhone

EDIT :
I've been able to resolve this, after finding that iOS uploads every image as "image.jpg". In freeASPUpload.asp, I changed the following :
For Each fileItem In UploadedFiles.Items
filePath = path & fileItem.FileName
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = adTypeBinary
streamFile.Open
StreamRequest.Position=fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & FileName, adSaveCreateOverWrite
streamFile.close
Set streamFile = Nothing
fileItem.Path = filePath
Next
To :
For Each fileItem In UploadedFiles.Items
FileName = GetFileName(path, fileItem.FileName)
fileItem.FileName = FileName
filePath = path & fileItem.FileName
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = adTypeBinary
streamFile.Open
StreamRequest.Position=fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & FileName, adSaveCreateOverWrite
streamFile.close
Set streamFile = Nothing
fileItem.Path = filePath
Next
This is within the save function of the script. The GetFileName function iterates over what is in the folder already, and adds a number until it is unique. It then updates the file key to its new name. I've left an "image.jpg" file in the temp folder, so that it always finds one. That works for now.
What I've found, however, is for some reason, it flips the second photo out of the five that the form allows for..
I will try to fix that / look for others with the same issue. I've always had problems with iPhones and iPads rotating pictures, and it's never consistent.
I'm trying to grab multiple files from a mobile fleet of iPads and iPhones. Currently I have 5
<input type="file" name="fileX" accept="image/*">
This works fine in a browser (using free asp upload / classic ASP). In testing, it works with IOS, but only if I send one file. If I send more then one via the form, I get the error 'file not found'. It seems like the files aren't being sent at all.
The file not found kicks back when trying to manipulate the file via FSO.
Uploads here :
Dim Upload, fileName, fileSize, ks, i, fileKey
Set Upload = New FreeASPUpload
SaveFiles = ""
uploadsDirVar = "directory"
Upload.Save(uploadsDirVar)
ks = Upload.UploadedFiles.keys
Errors out here :
Set f=fs.GetFile(uploadsDirVar & "\" & Upload.UploadedFiles(fileKey).FileName)
Any ideas on how I can get around this? Everything I've read points towards the HTML5 multiple tag on a single input. However, in my scenario, this won't work. I'm also tying descriptions for the images to the fields based on field name, restricting the upload to 5, re-sizing the images on the action page before passing it to its final destination and attaching them to an email.
Any advice welcome, and thank you for your time!
**Edit
The issue seems to be that IOS names all uploads "image", coming from either the camera or the library. Now the problem is how to rename the image before the script attempts to upload it. From what I'm understanding, it needs to happen within the asp upload component before it places the file.
See the above edit for the answer. As for the flipped images - turns out they are flipped straight from the iPad. I checked the exif data and I'm not sure how to account for this in my system. If I find the answer, I'll post here.

Copying file from local to SharePoint server location

Now on my PC I can use explorer to open a location on our SP server (location eg http://sp.myhost.com/site/Documents/). And from there I can copy/paste a file from eg my C:\ drive.
I need to replicate the copy process progmatically. FileCopy() doesn't do it - seems to be the http:// bit that's causing problems!
Does the server allow WebDAV access? If yes, there are WebDAV clients for Delphi available, including Indy 10.
In case if you are not using BLOB storage all SharePoint files are stored in the database as BLOB objects.
When you access your files with explorer you are using windows service which is reading files from SharePoiont and render it to you. This way you can copy and paste as soon as donwload them from an to SharePoint manually.
To be able to do this automatically you should achive this using the next SP API code:
using (SPSite site = new SPSite("http://testsite.dev"))
{
using (SPWeb web = site.OpenWeb())
{
using (FileStream fs = File.OpenRead(#"C:\Debug.txt"))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int) fs.Length);
SPList list = web.GetList("Lists/Test AAD");
SPFile f = list.RootFolder.Files.Add("/Shared Documents/"+Path.GetFileName(fs.Name), buffer);
}
}
}
This will add new "Debug.txt" file to the "Shared Documents" library read from the disk C. To do this for each file just loop through each file in the folder. You can open web only once and do the loop each time when you add file...
Hope it helps,
Andrew

system.io.directorynotfound -> But it works in Console

My files are referenced like so (it's all relative):
// WHERE YOU KEEP THE PAGE TITLE XML
public static string myPageTitleXML = "xml/pagetitles.xml";
and
using (StreamReader r = new StreamReader(myPageTitleXML))
{ //etc.. . .etc....etc..
}
I get system.io.directorynotfound, and "this problem needs to be shut down", when I double click the executable. But running it from the console works like a charm. What's wrong here?
I played around with attempting to set Environment.CurrentDirectory but couldn't get anything to work. Why should I have to do that anyway? It defeats the purpose of a relative path no?
responding.. .
"application" does not exist in the current context, i'll keep trying what people have mentioned, this is not a windows.form
testing
Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), myPageTitleXML); gives error URI formats are not supported, as does Path.GetFullPath(). Server.MapPath results in an error as well, this is currently offline
Well assuming this directory is somewhere under the directory in which your code is executing, it sounds like you can use ..
Application.ExecutablePath()
or
Application.StartUpPath()
.. to get an idea as to what your application is seeing when it goes in search of an 'xml' directory with the 'pagetitles.xml' file in it.
If the directory returned by one of these methods does not point where you thought it did, you'll need to move the location of your application or the location of this folder so that it is within the same directory as the app.
Hope this gets you on the right path.
So, when you run it from double clicking the executable, is there a file named pagetitles.xml in a folder named xml, where xml is a folder in the same location as the executable?
It's certainly possible to use relative paths like this, but I wouldn't really recommend it. Instead, maybe use something like:
string fileToOpen = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), myPageTitleXML);
using (StreamReader r = new StreamReader(fileToOpen))
{
//etc.. . .etc....etc..
}
Is this ASP.NET code? If so then you probably need to do MapPath("xml/pagetitles.xml")

Resources