Checking contents of Uploaded file - asp.net-mvc

I am using ASP.NEt MVC . I want to upload .zip files for which I am using html input file upload control on my view.
I want only .zip files to be uploaded.
I want to check that my .zip contains only two files - both having extensions .txt and one of them having name "start".
Can anyone please suggest me about how to check this? How can we assure that the uploaded .zip is really a zipped folder and not any other file having just .zip extension.
can we use HttpPostedFileBase.ContentType?
thanks in advance,
kaps

The ContentType is simply filled in by the client browser, so you can't really trust it. The only way is to try & parse the file on the server: use something like SharpZipLib to open the .zip file and confirm that it has two files in it.

You can use DotNetZip to determine whether file is a zip file or not. And you can do much more with dotnetzip.
You can verify like this
[HttpPost]
public ActionResult Index(FormItems item, HttpPostedFileBase files)
{
//check for zip file
try
{
ZipFile.CheckZip(files.FileName); //just pass the name of the file
}
catch
{
//not a zip file
}
}
OR
[HttpPost]
public ActionResult Index(FormItems item, HttpPostedFileBase files)
{
//check for zip file
try
{
ZipFile.Read(files.InputStream); //read the zip contents by passing the input stream
}
catch
{
//not a zip file
}
}
Make sure that you include namespace using Ionic.Zip; and add a reference to that dll as well.
Hope this helps

Related

Where is the downloaded file?

I'm using the Upload component in a Vaadin8 project to get a file up on the server, as shown in the source code on this page:
https://demo.vaadin.com/sampler/#ui/data-input/other/upload
After I choose the file on my pc and click upload, the window opens up just like in the sampler, and the progress bar goes all the way to the end, but the file is nowhere to be found in the project file system. Is there another step I'm supposed to be doing? How to I configure the destination folder for the uploaded files?
Taken from official documentation here Receiving upload:
The uploaded files are typically stored as files in a file system, in a database, or as temporary objects in memory. The upload component writes the received data to an java.io.OutputStream so you have plenty of freedom in how you can process the upload content.
So in your case, an uploaded file is stored as a temporary object. In V8 documentation example is cut-off, but it's presented in V7: Receiving Upload Data
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File("/tmp/uploads/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
new Notification("Could not open file<br/>",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
So the idea is that you could create a file yourself, once upload has succeed.

Stream multiple Excel files as one file

I want to deliver large Excel files using a webservice or httphandler.
As the Excel files can be very big in size, I want to split them up into smaller files, to decrease the memory footprint.
So I will have a master excelfile that contains the column headers and data.
And further files which will only contain data.
During download, I want to stream the master excel file first and then append all other related excel files as one download stream.
I don't want to zip them! It should be one file at the end
Is this possible?
Master excel file with headers:
All other files will look like this (without headers):
This will indeed return crap:
void Main()
{
CombineMultipleFilesIntoSingleFile();
}
// Define other methods and classes here
private static void CombineMultipleFilesIntoSingleFile(string outputFilePath= #"C:\exceltest\main.xlsx", string inputDirectoryPath = #"C:\exceltest", string inputFileNamePattern="*.xlsx")
{
string[] inputFilePaths = Directory.GetFiles(inputDirectoryPath, inputFileNamePattern);
Console.WriteLine("Number of files: {0}.", inputFilePaths.Length);
using (var outputStream = File.Create(outputFilePath))
{
foreach (var inputFilePath in inputFilePaths)
{
using (var inputStream = File.OpenRead(inputFilePath))
{
// Buffer size can be passed as the second argument.
inputStream.CopyTo(outputStream);
}
Console.WriteLine("The file {0} has been processed.", inputFilePath);
}
}
}
When you are requesting for file, do not download it at first request.
Request for file names to be downloaded in AJAX request.
For each file name received, prepare its path to the server.
Create hidden iFrames for each file path and specify src as file path for each file to be downloaded.
When iFrame's src attribute is set, it will navigate to the file path and each iFrame will download single file, so multiple iFrame downloads multiple files.
You cannot download multiple files in single request. As if you will append the stream of multiple files, it will create a garbage file, a single garbage file.

How to access a list of all files in resource folder of my project?

I have some .TXT files saved in Resource folder of my project. I want to display a list to user in which all files from resource folder are shown and user can select the file he desires.
Later on i will read the user selected file and show it on screen.
Take a look at the NSBundle function pathsForResourcesOfType:inDirectory: That will give you a list of the paths to all the files in a sub-bundle of a bundle. if you call that method on the main bundle you'll get a list of all the files of a certain type in a sub-directory of the main bundle.
(I have no idea how to make use of these functions from xamarin.)
This gets FileInfo's on all txt files in the resources:
var fileInfos = NSBundle.GetPathsForResources(".txt", path)
.Select(a => new FileInfo(a));
Now you have the short name, full name etc to play with:
foreach (var fileInfo in fileInfos)
{
System.Diagnostics.Debug.WriteLine(fileInfo.Name);
using (var streamReader = new StreamReader(new FileStream(fileInfo.FullName, FileMode.Open)))
{
System.Diagnostics.Debug.WriteLine(streamReader.ReadToEnd());
}
}

Saving an XML file in a different directory from a custom action

How can I update the following code to save in a directory of my choice on IIS. Currently it will only save in my downloads directory with the file name of the path.
E.g.. the following example saves in my downloads directory as
C--inetpub-wwwroot-sitename-Feeds-reports.xml
[HttpGet]
public XmlActionResult GetXmlData()
{
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(Server.MapPath("~/reports.xml"));
var xml = XElement.Load(reader);
//I want to save the file to the following destination but this saves it with the file name of the destination in my downloads directory
return new XmlActionResult(xml.ToString(), Server.MapPath("~/Feeds/reports.xml"));
}
EDIT
I want to move the reports.xml file from the current directory to the Feeds directory.

Excel doesn't want to open XLSX files downloaded through ASP output

I use ASP MVC3 framework, created an Excel file and outputted it using FileResult action with content type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".
When attempting to open it Excel just says "file is corrupt and cannot be opened."
When I open the source generated Excel file that was used to send the output it works without any problems. I also run file comparison on the bytes for both copies and the files are identical. I tried to email the corrupt file to myself and the attachment opens fine.
This leads me to believe it's a problem with headers or some sort of Excel/Windows security config.
If it is the latter, then I need a solution that won't make clients change their security settings.
EDIT - Found the setting:
I've found what setting causes this - "Enable protected view from files originated from the internet" in Excel's Trust Center / Protected View settings.
So I guess the question is - Is there a way for the file to appear trusted?
Here are the response headers:
Cache-Control:private
Content-Disposition:attachment;
filename="Report - Monday, March 19, 2012.xlsx" Content-Length:20569
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
The action method that makes the output:
[HttpPost]
public virtual FileResult Export()
{
try
{
...
string newFilePath = createNewFile(...);
string downloadedFileName = "Report - " + DateTime.Now.ToString("D") + ".xlsx";
return File(newFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", downloadedFileName);
}
catch (Exception ex)
{
...
}
}
How I create the Excel file:
I have a template XLSX file witch column names and some pivot charts in other sheets. From C# I create a copy of this template and then call SQL Server which outputs data into 1st sheet using OLEDB connector:
set #SQL='insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;Database=' + #PreparedXLSXFilePath + ';'', ''SELECT * FROM [Data$]'') ...
Thanks in advance for any help.
You would need a digital signature in your Excel file. How to do this from code is another question.
More info here:
http://www.delphifaq.com/faq/windows_user/f2751.shtml

Resources