asp.net/HTML file upload control not uploading mutiple files as expected - html

I am using asp.net file control. I am uploading multiple files. The problem is when I select two or multiple files, it's only upload one file multiple times. I mean if I select two different images, It will upload the first image two times. And if I select three images, then it will upload first image three times.
My file upload control is following,
<asp:FileUpload runat="server" ID="file" multiple />
And I server side code is following
protected void click(object sender, EventArgs e) {
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = Request.Headers["X-File-Name"];
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
file.SaveAs(savedFileName);
}
}
I have no idea why this is behaving this way. When I debug the server side code, it's giving me different names of files from "Request.Headers["X-File-Name"]" but somehow it's uploading same content (the first image from the multiple images that I try to upload)

You can get posted files from file upload control if you are using ASP.NET > 4.0 like this
foreach (HttpPostedFile f in file.PostedFiles)
{
//HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = f.ContentLength;
string fileName = f.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
f.SaveAs(savedFileName);
}
With ASP.NET 4.0 or less aslo available in 4.0 and above
HttpFileCollection fc = Request.Files;
for (int i = 0; i < fc.Count; i++)
{
HttpPostedFile f = fc[i];
int fileSizeInBytes = f.ContentLength;
string fileName = f.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
// IMPORTANT! Make sure to validate uploaded file contents, size, etc. to prevent scripts being uploaded into your web app directory
string savedFileName = Path.Combine(#"D:\Temp\", Guid.NewGuid().ToString() + ".jpg");
f.SaveAs(savedFileName);
}

Related

ABCPDF with MSHTML engine not loading .JPG files

I am using ABCPDF and using the MSHTML engine for a certain report. It loads .PNG files fine, and our extensionless handler images, but when it comes to .jpg it shows an X. The pure HTML loads fine, but converting the html to PDF it doesnt load.
The other images in the screenshot are either PNG or extensionless. Also the Chrome Engine loads the image.
I even did a test with the same exact image, just different in how its sent to the browser. The first one is the image handler, that returns a JPG, and the second is reading the file directly from the file system. The handler works, but the one with the extension doesnt.
Any clue on why this is happening with the MSHTML engine?
/assets/files/210057 <-- Loads
/assets/files/210057.jpg <-- DOESNT
string theDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\files\";
string theURL = "file://" + theDir + "source.html";
using (Doc doc = new Doc())
{
doc.MediaBox.String = "Letter";
// Convert HTML
doc.Pos.Y = 0;
doc.Rect.Inset(0, 0);
doc.HtmlOptions.Engine = EngineType.MSHtml;
doc.Rect.String = doc.MediaBox.String;
var w = doc.MediaBox.Width;
var h = doc.MediaBox.Height;
var l = doc.MediaBox.Left;
var b = doc.MediaBox.Bottom;
doc.Transform.Rotate(90, l, b);
doc.Transform.Translate(w, 0);
doc.Rect.Width = h;
doc.Rect.Height = w;
int theID = doc.AddImageUrl(theURL, true, 800, true);
doc.SetInfo(doc.GetInfoInt(doc.Root, "Pages"), "/Rotate", "90");
while (true)
{
if (!doc.Chainable(theID)) break;
doc.Page = doc.AddPage();
theID = doc.AddImageToChain(theID);
}
for (int i = 1; i <= doc.PageCount; i++)
{
doc.PageNumber = i;
doc.Flatten();
}
string outFile = Path.Combine(theDir, $"out{XSettings.Version}{doc.HtmlOptions.Engine}.pdf");
doc.Save(outFile);
doc.Clear();
}
Well it turned out to be this added customHeader in the Web.Config. I will now either switch to ABCChrome or try to ignore this on images with a url rewrite rule.
<add name="X-Content-Type-Options" value="nosniff" />

How to convert a json object into .csv file and how to export using Ionic 2 + angular 2?

I'm using a function in my angular 2 application to convert and export a JSON data into .CSV. The below is my function and is working fine in angular 2 application
(web). The Same I tried to use in mobile app which I developed using Ionic 2, it is not working in mobile app. Is there any way to do this?
Thanks!
saveAsCSV() {
let sampleJson : any = [{name:'ganesh', age:'24'},{name:'ramesh', age:'24'},{name:'suresh', age:'24'}]
this.saveData = [];
let a = document.createElement("a");
a.setAttribute('style', 'display:none;');
document.body.appendChild(a);
let csvData = ConvertToCSV(sampleJson);
let blob = new Blob([csvData], { type: 'text/csv' });
let url= window.URL.createObjectURL(blob);
a.href = url;
a.download = 'sample.csv';
a.click();
}
ConvertToCSV(objArray) {
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
let str = '';
let row = "";
for (let index in objArray[0]) {
//Now convert each value to string and comma-separated
row += index + ',';
}
row = row.slice(0, -1);
//append Label row with line break
str += row + '\r\n';
for (let i = 0; i < array.length; i++) {
let line = '';
for (let index in array[i]) {
if (line != '') line += ',';
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
Use "cordova-plugin-file" to export csv in Ionic 2.
https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/
If you see the following error -
code:1 message:"NOT_FOUND_ERR"
Add one of the following lines in config.xml to resolve it.
<preference name="AndroidPersistentFileLocation" value="Internal" />
<preference name="AndroidPersistentFileLocation" value="Compatibility" />
As explained in the documentation of the plugin, you can use one of these two option to:
choose whether to store files in the internal
file storage location, or using the previous logic, with a preference
in your application's config.xml file. Without this line, the File plugin will use Internal as the
default. If a preference tag is present, and is not one of these
values, the application will not start.
If your application has previously been shipped to users, using an
older (pre- 3.0.0) version of this plugin, and has stored files in the
persistent filesystem, then you should set the preference to
Compatibility if your config.xml does not specify a location for the
persistent filesystem. Switching the location to "Internal" would mean
that existing users who upgrade their application may be unable to
access their previously-stored files, depending on their device.
If your application is new, or has never previously stored files in
the persistent filesystem, then the Internal setting is generally
recommended.

Save PDF file in Isolated storage for read/write operation in windows phone 8

For my application I want to put PDF file into isolated storage for browsing the same pdf file as per
my requirement.
Is it possible to write PDF files in isolated storage?
This is my code:
var AppIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
var FileName = AppIsolatedStorage.CreateFile(FName);
string FilePath = uriAddress.LocalPath;
Uri FileDataa = new Uri(FilePath, UriKind.Relative);
var FileData = Application.GetResourceStream(FileDataa);
byte[] bytes = new byte[4096];
int Count;
while ((Count = FileData.Stream.Read(bytes, 0, 4096)) > 0)
{
FileName.Write(bytes, 0, Count);
}
FileName.Close();
Its only creating a file name inside the isolated storage with unknown format.
I also gone through this link http://our.componentone.com/groups/topic/save-pdf-file-to-local-storage/
but in windows phone8/8.1 no assembly supporting c1PdfViewer1.
Is there any solution for this issue?

PDFTron Convert from HTML to PDF on WinRT

I'm writing a Windows 8 Store App using WinJS. My app needs to generate PDFs with text and graphs. I was under the impression that PDFtron could convert HTML to PDF, but that does not seem to be the case for an App Store application. Is this true?
The front end uses WinJS/HTML and Telerik Radcharts to render graphs in SVG. I then pipe the DOM down to disk as an HTML file. It shows the graph and numbers nicely. I want to convert the HTML to a PDF to preserve the styling as well as the content.
The WinRT version does not come with the HTML2PDF assembly or the .Convert() method. Is it somewhere else? I've searched the docs, samples, and the web.
PDFTron's PDFNet SDK on WinRT does not support HTML to PDF conversion (as at version 6.2).
Here is the response I received from PDFTron support on this question:
While the PDFNet SDK on WinRT cannot itself convert from HTML
to PDF, the PDFNet SDK on Windows desktop can do so. You can find
sample code for for HTML to PDF conversion at
http://www.pdftron.com/pdfnet/samplecode.html#HTML2PDF.
Some of our clients send HTML to a server of theirs, where
PDFNet can convert the HTML to PDF. Note that on Windows
desktop there are many conversion options, including converting Office
to PDF and converting any printable document format to PDF.
EVO has implemented the following solution to convert HTML to PDF in WinRT and Windows Store Applications. You can find a compelte code sample in that page.
The copy of the code sample is:
private async void buttonConvertUrlToPdf_Click(object sender, RoutedEventArgs e)
{
// If another conversion is in progress then ignore current request
bool ignoreRequest = false;
lock(pendingConversionSync)
{
if (pendingConversion)
ignoreRequest = true;
else
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
pendingConversion = true;
}
}
if (ignoreRequest)
return;
try
{
String serverIP = textBoxServerIP.Text;
uint port = uint.Parse(textBoxServerPort.Text);
HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, port);
// set service password if necessary
if (textBoxServicePassword.Text.Length > 0)
htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;
// set HTML viewer width
htmlToPdfConverter.HtmlViewerWidth = int.Parse(textBoxHtmlViewerWidth.Text);
// set HTML viewer height if necessary
if (textBoxHtmlViewerHeight.Text.Length > 0)
htmlToPdfConverter.HtmlViewerHeight = int.Parse(textBoxHtmlViewerHeight.Text);
// set navigation timeout
htmlToPdfConverter.NavigationTimeout = int.Parse(textBoxHtmlViewerWidth.Text);
// set conversion delay if necessary
if (textBoxConversionDelay.Text.Length > 0)
htmlToPdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text);
// set PDF page size
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();
// set PDF page orientation
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();
// set margins
htmlToPdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text);
htmlToPdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text);
// add header
if (checkBoxAddHeader.IsChecked != null && (bool)checkBoxAddHeader.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
DrawHeader(htmlToPdfConverter, true);
}
// add footer
if (checkBoxAddFooter.IsChecked != null && (bool)checkBoxAddFooter.IsChecked)
{
htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
DrawFooter(htmlToPdfConverter, true, true);
}
string urlToConvert = textBoxUrl.Text;
string errorMessage = null;
// Convert the HTML page from give URL to PDF in a buffer
byte[] pdfBytes = await Task.Run<byte[]>(() =>
{
byte[] resultBytes = null;
try
{
resultBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);
}
catch (Exception ex)
{
errorMessage = String.Format("Conversion failed. {0}", ex.Message);
return null;
}
return resultBytes;
});
if (pdfBytes == null)
{
MessageDialog errorMessageDialog = new MessageDialog(errorMessage, "Conversion failed");
await errorMessageDialog.ShowAsync();
return;
}
// Save the PDF in a file
Windows.Storage.StorageFolder installedLocation = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile outStorageFile = installedLocation.CreateFileAsync("EvoHtmlToPdf.pdf", CreationCollisionOption.ReplaceExisting).AsTask().Result;
FileIO.WriteBytesAsync(outStorageFile, pdfBytes).AsTask().Wait();
// Open the file in a PDF viewer
await Windows.System.Launcher.LaunchFileAsync(outStorageFile);
}
finally
{
lock (pendingConversionSync)
{
msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
pendingConversion = false;
}
}
}

Upload multiple files at once using GWT

I'm desperately trying to enable the multiple-property to users of my webside. User should be able to upload a bunch of PDF-files to my server without choosing each file separately. I'm using gwt-upload for my uploads. Sadly the
MultiUploader
does not actually lets the user select several files at once, but you have to click the "Browse"-Button for every file again and select in in the browser.
I researched and realised that I need to have something like this
<input name='uploads[]' type="file" multiple>
Setting the "multiple"-property at the input created from gwt-upload does the trick so far that the opening file-dialog lets me select several files, but then the upload does not start / work anymore.
I could not find any example using a multi-file-input with gwt. It would be perfect if there is a way to do this with gwt-upload because I do not really want to implement the whole upload logic by myself again!
Thanks a lot!
I use a more simple solution.
defaultUploader = new MultiUploader();
IFileInput ctrl = defaultUploader.getFileInput();
DOM.setElementProperty((ctrl).getElement(), "multiple", "multiple");
The solution is pretty simple. gwt-upload has a class Uploader which is able to do multiple uploads. The servlet code suggested in the wiki of gwt-upload is already capable of handling multiple uploads.
I had to change somethings in the Uploader class (source is fully available, so I just copied it and replaced the parts I needed). To access filenames and filesizes of the selected files I created a simple native method:
private static native String getFilesSelected() /*-{
var count = $wnd.$('input:file')[0].files.length;
var out = "";
for (i = 0; i < count; i++) {
var file = $wnd.$('input:file')[0].files[i];
out += file.name + ';' + file.size + ";";
}
return out;
}-*/;
whichs return value I split by ; to get the needed results.
And you need to replace the uploaders FileInput (setFileInput()) with a custom one, which sets the multiple property to the input. I use a wrapper class like this:
public class MyFileInput implements IFileInput {
private final FileUpload fu;
public MyFileInput() {
fu = new FileUpload();
DOM.setElementProperty(fu.getElement(), "multiple", "multiple");
}
}
you obviously need to implement the other methods of IFileInput, I linked them all through to fu. Two had no equivalent method, but I dont use them, so no problem here ...
Here's what I ended up with that I believe works on all browsers:
form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
form.add(new HTML("<input type='file' id='fileselect' name='fileselect[]' multiple />"));
then on the server side I'm just using "org.apache.commons.fileupload" stuff.
Yeah some people may not like the HTML element in the form, but here is how you CAN get the input element from it if you want:
protected Element getFileSelectElement() {
HashMap<String, Element> idMap = Maps.newHashMap();
GuiUtil.parseIdsToMap(inputField.getElement(), idMap);
Element input = idMap.get("fileselect");
return input;
}
public static void parseIdsToMap(Element element, HashMap<String, Element> idMap) {
int nodeCount = element.getChildCount();
for (int i = 0; i < nodeCount; i++) {
Element e = (Element) element.getChild(i);
if (e.getId() != null) {
idMap.put(e.getId(), e);
}
}
}
and finally... if you want to get access to the list of files the user selected, on the browser side, here's what I have:
public static native String getFileNames(Element input) /*-{
var ret = "";
//microsoft support
if (typeof (input.files) == 'undefined'
|| typeof (input.files.length) == 'undefined') {
return input.value;
}
for ( var i = 0; i < input.files.length; i++) {
if (i > 0) {
ret += ",";
}
ret += input.files[i].name;
}
return ret;
}-*/;