Embedding PDF opened via input file element in HTML - html

I have a simple web app that I am needing someone to select a .pdf from a file server and then display that .pdf on the web page.
I can get the user to select the .pdf via something like <input type="file" id="myFile">
I can also embed a .pdf into an iframe to display on the web app nicely with <iframe src="//path/to/file.pdf" width="100%" height="500px"></iframe>
But how do I display the .pdf the user selected from the input? Is there a way I can pass the value of the input into the src of the iframe? Can I open the .pdf in a new tab or a new html file so I don't have to refresh the entire page?

For anyone needing help with this I found a solution that worked for me.
I created an input for the file I'm wanting to upload. This input calls a JS function that is defined below.
<input type="file" id="file-open" onchange="previewFile()" hidden="hidden" accept=".pdf"><br>
Then created an iframe with size I wanted
<iframe src="" id="iframe-pdf" width="1200px" height="800px"></iframe>
Finally I used JavaScript to convert the file to base64 and use FileReader to open the file within the iframe
function previewFile() {
const preview = document.querySelector('iframe');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
var filename = file.name;
reader.addEventListener("load", function () {
// convert file to base64 string
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>

Related

How to set value of an input with type of image file in HTML? [duplicate]

How can I set the value of this?
<input type="file" />
You cannot set it to a client side disk file system path, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
You can only set it to a publicly accessible web resource as seen in this answer, but this is clearly not the same as a client side disk file system path and it's therefore useless in that context.
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
Not an answer to your question (which others have answered), but if you want to have some edit functionality of an uploaded file field, what you probably want to do is:
show the current value of this field by just printing the filename or URL, a clickable link to download it, or if it's an image: just show it, possibly as thumbnail
the <input> tag to upload a new file
a checkbox that, when checked, deletes the currently uploaded file. note that there's no way to upload an 'empty' file, so you need something like this to clear out the field's value
You can't. And it's a security measure. Imagine if someone writes JS that sets file input value to some sensitive data file?
I have write full example for load URL to input file, and preview
you can check here
1
https://vulieumang.github.io/vuhocjs/file2input-input2file/
in short you can use this function
function loadURLToInputFiled(url){
getImgURL(url, (imgBlob)=>{
// Load img blob to input
// WIP: UTF8 character error
let fileName = 'hasFilename.jpg'
let file = new File([imgBlob], fileName,{type:"image/jpeg", lastModified:new Date().getTime()}, 'utf-8');
let container = new DataTransfer();
container.items.add(file);
document.querySelector('#file_input').files = container.files;
})
}
// xmlHTTP return blob respond
function getImgURL(url, callback){
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
As everyone else here has stated: You cannot upload just any file automatically with JavaScript.
HOWEVER! If you have access to the information you want to send in your code (i.e., not C:\passwords.txt), then you can upload it as a blob-type, and then treat it as a file.
What the server will end up seeing will be indistinguishable from someone actually setting the value of <input type="file" />. The trick, ultimately, is to begin a new XMLHttpRequest() with the server...
function uploadFile (data) {
// define data and connections
var blob = new Blob([JSON.stringify(data)]);
var url = URL.createObjectURL(blob);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myForm.php', true);
// define new form
var formData = new FormData();
formData.append('someUploadIdentifier', blob, 'someFileName.json');
// action after uploading happens
xhr.onload = function(e) {
console.log("File uploading completed!");
};
// do the uploading
console.log("File uploading started!");
xhr.send(formData);
}
// This data/text below is local to the JS script, so we are allowed to send it!
uploadFile({'hello!':'how are you?'});
So, what could you possibly use this for? I use it for uploading HTML5 canvas elements as jpg's. This saves the user the trouble of having to open a file input element, only to select the local, cached image that they just resized, modified, etc.. But it should work for any file type.
You need to create a DataTransfer and set the .files property of the input.
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);//your file(s) reference(s)
document.getElementById('input_field').files = dataTransfer.files;
the subject is very old but I think someone can need this answer!
<input type="file" />
<script>
// Get a reference to our file input
const fileInput = document.querySelector('input[type="file"]');
// Create a new File object
const myFile = new File(['Hello World!'], 'myFile.txt', {
type: 'text/plain',
lastModified: new Date(),
});
// Now let's create a DataTransfer to get a FileList
const dataTransfer = new DataTransfer();
dataTransfer.items.add(myFile);
fileInput.files = dataTransfer.files;
</script>
Define in html:
<input type="hidden" name="image" id="image"/>
In JS:
ajax.jsonRpc("/consulta/dni", 'call', {'document_number': document_number})
.then(function (data) {
if (data.error){
...;
}
else {
$('#image').val(data.image);
}
})
After:
<input type="hidden" name="image" id="image" value="/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8U..."/>
<button type="submit">Submit</button>
Actually we can do it.
we can set the file value default by using webbrowser control in c# using FormToMultipartPostData Library.We have to download and include this Library in our project. Webbrowser enables the user to navigate Web pages inside form.
Once the web page loaded , the script inside the webBrowser1_DocumentCompleted will be executed.
So,
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FormToMultipartPostData postData =
new FormToMultipartPostData(webBrowser1, form);
postData.SetFile("fileField", #"C:\windows\win.ini");
postData.Submit();
}
Refer the below link for downloading and complete reference.
https://www.codeproject.com/Articles/28917/Setting-a-file-to-upload-inside-the-WebBrowser-com

NodeJS load a json from a file selector without reloading webpage

Has anyone done this?
I need to be able to grab a JSON file from a input file selector from HTML, after that read it, parse it and show it in the webpage.
The page cannot reload and I don't need to upload/copy it to any of my folders. I just need to read it and show it without reloading the webpage.
Any ideas? I'm on Nodejs. I'm serving static html pages. Apparently it's simple but I'm struggling a lot.
HTML:
<input type="file" onchange='getContent(this)' />
<div id="file-content"></div>
JS:
function getContent(content) {
if (content.files && content.files[0]) {
var contentReader = new FileReader();
contentReader.onload = function(e) {
var output = e.target.result;
document.getElementById('file-content').innerHTML = output;
};
contentReader.readAsText(content.files[0]);
}
}
You can see live preview here

Firebase download url in <a> opens csv file in browser

I use Firebase to generate a download link in AngularJS as follows:
self.getDownloadUrl = function(storage_ref) {
var q = $q.defer();
var storage = firebase.storage();
storage.ref(storage_ref).getDownloadURL().then(function(url) {
q.resolve(url);
}).catch(function(error) {
q.reject(error);
});
return q.promise;
};
Then I bind the url to an object scope.downloadUrl. In my DOM I then try to download the file as follows:
Download
However, when I click on this link, it opens my .csv file in the browser (looks like a text file with comma separated, tested it on Chrome and Edge). How can I prevent this and just enforce a proper download?

How to create a WinRT Book reader application

I'd like to create an application that receives formatted text (RTF) or html, renders it an show it page by page..
Is there any control that aims to do that?
I tried to use the RichEditBox control to load a file but it stucks during the operation:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"myFile.rtf");
using (var memstream = await file.OpenReadAsync())
{
MainText.Document.LoadFromStream(Windows.UI.Text.TextSetOptions.ApplyRtfDocumentDefaults, memstream);
}
I tried to load an HTML file this way:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"myFile.htm");
var stream = await file.OpenAsync(FileAccessMode.Read);
string app;
using (StreamReader rStream = new StreamReader(stream.AsStream()))
{
app = rStream.ReadToEnd();
}
myWebView.NavigateToString(app);
But I cannot find a way to "count" the lenght of the parsed text to chunk it in pages..
There is any other way or library to do that? Any example online?
If you want to show your HTML contents in pages then you can use RichTextBlock with RichTextBlockOverflow. RTF is not supported to RichTextBlock.
how to inject RTF file to RichTextBlock in c#/xaml Windows store app
Showing Html in WinRT with RichTextBlock or other component
XAML text display sample

HTML input tag file handling

In this code for the PDF reader pdf-js there is an input tag to let the user upload an input file
<input id="fileInput" class="fileInput" type="file" oncontextmenu="return false;" style="visibility: hidden; position: fixed; right: 0; top: 0" />
This input tag is not a part of any form. Once the user uploads the file, where does it go? Where is the code that processes the file? (I'm asking in general, not necessarily specific to this piece of code.)
"Then it's interesting. This code doesn't have server side"
No, It doesn't.
Pdf.js is a client side program that written with javascript. So that works on javascript side.
It actually takes the file that you wanna show, and does whatever must be done like converting the buffer to Uint8Array than renders it.
All processes happen on javascript side. No server side, no file upload.
Here is an article about reading local files in javascript
Here is the related part of code in pdf.viewer.js
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFView.open(uint8Array, 0);
};
var file = files[0];
fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
document.getElementById('viewBookmark').setAttribute('hidden', 'true');
document.getElementById('download').setAttribute('hidden', 'true');
}, true);