How to force download a file with JavaScript? [duplicate] - javascript

This question already has answers here:
Is it possible to initiate a download prompt in the browser for recognized MIME types using only JavaScript (client-side approach)?
(3 answers)
Closed 8 years ago.
I have a jQuery ajax form where a user submits his email, once the form has been submitted, the user should get an automated download of a file, the form looks like this:
$(".email-form").submit(function(event) {
event.preventDefault();
var $form = $(this),
form_email = $form.find("input[name='email']").val(),
url = $form.attr("action");
var posting = $.post(url, { email: form_email });
posting.done(function() {
$(".popup-design").hide();
$("input[name='email']").val("");
$("#done").show();
});
});
and also I need to have to user automatically download a file of my choice when posting is done. How can I do that?

You will have to:
Create an iframe and add it to your document.
Set the iframe's SRC to be a URL to the download.
Have the server send the correct headers to cause a download prompt.
Edit - Found this question which is very much related
Using jQuery and iFrame to Download a File

Related

Can javascript display text of any external file with any extension? [duplicate]

This question already has answers here:
Local file access with JavaScript
(14 answers)
How to read a text file containing html without using input type file in JavaScript?
(2 answers)
Closed 3 years ago.
Lets consider that I have a text file named text.txt. So, now I made a file named showtext.html in which I have to write javascript such that it can display the text present in text.txt. I assume it would be like :
Text ( text.txt )
Show me up !
HTML ( showtext.html )
<!DOCTYPE html>
<html>
<body>
<script>
var src = "text.txt";
document.write( value.get( src ) );
</body>
</html>
Output of showtext.html
Show me up !
In, the above function the value.get() gets and then writes the value of the text.txt. So, can javascript really do such ? How can I make the value.get() ? Will it support only .txt extension or can support any custom extension ? Or this can only be done with PHP ?
"Local" means "all client, no server" :) If you don't have a server, you can't use things like fetch() (as far as I know, security restrictions prevent that). But you can read a file from the local computer on the client as long as the user selects the file themselves. You can't just read any arbitrary file from the client's computer (again, for security reasons).
If you're okay with letting the user select the file, look into the FileReader API.
HTML:
<input type='file' id='fileSelector' />
JS:
const fileInput = document.getElementById('fileSelector');
fileInput.addEventListener('change', event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.addEventListener('load', readEvent => {
// In here, readEvent.target.result will have the text of the file for you to work with.
});
reader.readAsText(file);
});

how make the file path dynamic [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
Hi I wrote the below Java code to email a file as attachement. It works fine if I provide a sample filepath. But, I want it to take the file path browsed by the user in the Front End
//code to attach the file
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart.setText(sb.toString());
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
//String filename = filePath;
String filename = "C:/Users/S.Mandava/Documents/ContactusAction.java";
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
msg.setContent(multipart);
System.out.println("Attaching the file");
Transport.send(msg);
Form example,
I want the system to take the file path uploaded in the below form when the user clicks on submit and the file should be sent as an attachment in an email
<form >
<input type ="file"/ id="multiple_files" name="multiple_files" multiple><br/>
<button>Submit</button>
</form>
How do I do it? I want to use JSP and JavaScript on the Front End and Java on the Back End. I am having difficulty in getting the file path.
As #Rishal_dev_singh said, search for examples, Google is your friend... What you do is an InputStream, you don't define a path

How to show error message instantly when files not of image types using fileupload jQuery [duplicate]

This question already has answers here:
blueImp/jquery file upload - How do I get the error message if the file type was not accepted?
(9 answers)
Closed 3 years ago.
I am using jQuery File Upload Plugin 5.21 to upload files to my site. My need is to show error message instantly when a file type not like image is added(by checking file extension). how to use built in function to check this operation like _onSend _beforeSend but not aware of using it.
(If possible can show a demo?).Thankx in advance
You can use below code.
JavaScript
add: function (e, data) {
var goUpload = true;
var uploadFile = data.files[0];
if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test(uploadFile.name)) {
common.notifyError('You must select an image file or your message.......');
goUpload = false;
}if (goUpload == true) {
data.submit();
}
},

How to use input type file in phonegap? [duplicate]

This question already has answers here:
How to upload file with Phonegap and JqueryMobile?
(2 answers)
Closed 3 years ago.
How to use html file attribute in phonegap ? so that i can browse any .txt file from my android device and upload it to the server??
I read file transfer method in phonegap documentation but according to that it is possible to upload files to the server only through url.But is it possible in normal way like :
<input type=file /><button>upload</button>
input type="file" accept="image/*" doesn't work in phone gap? i looked at this link but that says only for images .
But how to upload the text files ?
Any help??
Can anybody answer this?
You can't use input file on Phonegap. It's not supported. You need make something like this:
function uploadDatabase(callback) {
// file.entry accessible from global scope; see other tutorial
var filepath = file.entry.fullPath,
uploadOptions = new FileUploadOptions(),
transfer = new FileTransfer(),
endpoint = "http://facepath.com/payload";
uploadOptions.fileKey = "db";
uploadOptions.fileName = "database.db";
uploadOptions.mimeType = "text/plain";
transfer.upload(filepath, endpoint, transferComplete,
transferError, uploadOptions);
}
in mime type put the type of file
I wrote this answer "You can't use input file on Phonegap. It's not supported.". Check the solution on https://stackoverflow.com/a/13862151/1853864

Is robust javascript-only upload of file possible

I want a robust way to upload a file. That means that I want to be able to handle interruptions, error and pauses.
So my question is: Is something like the following possible using javascript only on the client.
If so I would like pointers to libraries, tutorials, books or implementations.
If not I would like an explanation to why it's not possible.
Scenario:
Open a large file
Split it into parts
For each part I would like to
Create checksum and append to data
Post data to server (the server would check if data uploaded correctly)
Check a web page on server to see if upload is ok
If yes upload next part if no retry
Assume all posts to server is accompanied by relevant meta data (sessionid and whatnot).
No. You can, through a certain amount of hackery, begin a file upload with AJAX, in which case you'll be able to tell when it's finished uploading. That's it.
JavaScript does not have any direct access to files on the visitor's computer for security reasons. The most you'll be able to see from within your script is the filename.
Firefox 3.5 adds support for DOM progress event monitoring of XMLHttpRequest transfers which allow you to keep track of at least upload status as well as completion and cancellation of uploads.
It's also possible to simulate progress tracking with iframes in clients that don't support this newer XMLHTTPRequest additions.
For an example of script that does just this, take a look at NoSWFUpload. I've been using it succesfully for about few months now.
It's possible in Firefox 3 to open a local file as chosen by a file upload field and read it into a JavaScript variable using the field's files array. That would allow you to do your own chunking, hashing and sending by AJAX.
There is some talk of getting something like this standardised by W3, but for the immediate future no other browser supports this.
Yes. Please look at the following file -
function Upload() {
var self = this;
this.btnUpload;
this.frmUpload;
this.inputFile;
this.divUploadArea;
this.upload = function(event, target) {
event.stopPropagation();
if (!$('.upload-button').length) {
return false;
}
if (!$('.form').length) {
return false;
}
self.btnUpload = target;
self.frmUpload = $(self.btnUpload).parents('form:first');
self.inputFile = $(self.btnUpload).prev('.upload-input');
self.divUploadArea = $(self.btnUpload).next('.uploaded-area');
var target = $(self.frmUpload).attr('target');
var action = $(self.frmUpload).attr('action');
$(self.frmUpload).attr('target', 'upload_target'); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', '/trnUpload/upload'); //change the form's action to the upload iframe function page
$(self.frmUpload).parent("div").prepend(self.iframe);
$('#upload_target').load(function(event){
if (!$("#upload_target").contents().find('.upload-success:first').length) {
$('#upload_target').remove();
return false;
} else if($("#upload_target").contents().find('.upload-success:first') == 'false') {
$('#upload_target').remove();
return false;
}
var fid = $("#upload_target").contents().find('.fid:first').html();
var filename = $("#upload_target").contents().find('.filename:first').html();
var filetype = $("#upload_target").contents().find('.filetype:first').html();
var filesize = $("#upload_target").contents().find('.filesize:first').html();
$(self.frmUpload).attr('target', target); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', action); //change the form's
$('#upload_target').remove();
self.insertUploadLink(fid, filename, filetype, filesize);
});
};
this.iframe = '' +
'false' +
'';
this.insertUploadLink = function (fid, filename, filetype, filesize) {
$('#upload-value').attr('value', fid);
}
}
$(document).ready(event) {
var myupload = new Upload();
myupload.upload(event, event.target);
}
With also using PHP's APC to query the status of how much of the file has been uploaded, you can do a progress bar with a periodical updater (I would use jQuery, which the above class requires also). You can use PHP to output both the periodical results, and the results of the upload in the iframe that is temporarily created.
This is hackish. You will need to spend a lot of time to get it to work. You will need admin access to whatever server you want to run it on so you can install APC. You will also need to setup the HTML form to correspond to the js Upload class. A reference on how to do this can be found here http://www.ultramegatech.com/blog/2008/12/creating-upload-progress-bar-php/

Categories

Resources