i have a link that allows me to downlowd a text file in my web page but the problem is that i want the user to be able to chose where to save the file i mean when he clicks the link a window should be opened so he can save the file wherever he likes can any one tell me how to do that? thx .
here is a part of my code:
$fichierres=fopen('res.txt','a');
ftruncate($fichierres,0);
...
fputs($fichierres, $t."\r\n");
...
fclose($fichierres);
echo' <div style="text-align:center"><br> <button id="download" width="100px" class="styled-button-8"><b>Download</b></button></div><br>';
Most browsers will auto-open any file that they can read - exactly how they should work. This includes .txt files, there's nothing that you can do to prevent this.
What you can do is provide the link as an anchor (Download) and provide a message next to the link telling the user to "Right click / Save link as..." to download - this will allow them to save the file rather than download.
The exact option in the right click menu will differ between browsers but it's always something along the lines of "Save Link As...".
http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
19.5.1 Content-Disposition
The Content-Disposition response-header field has been proposed as a
means for the origin server to suggest a default filename if the user
requests that the content is saved to a file. This usage is derived
from the definition of Content-Disposition in RFC 1806 [35].
content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )
An example is
Content-Disposition: attachment; filename="fname.ext"
In PHP, you would use header function to send this header. Note that this must be called before any data is sent.
header('Content-Disposition: attachment; filename="fname.ext"');
Related
I have a absolute file url.
let fileUrl="https://xyz.blob.core.windows.net/aggregator/merchant/docs/45.txt?st=2018-06-11T10%3A09%3A43Z&se=2018-06-12T10%3A09%3A43Z&sp=r&sv=2017-04-17&sr=c&sig=ugiw0CuNXr0".
On clicking of a button, this file needs to get downloaded.
<button onClick={()=> {}>Download</button>
How can I achieve this using reactjs?
Just link to it.
<a href={fileUrl}>Download</a>
A better way would be to not do it programatically:
<a href={fileUrl} download>
Download
</a>
If you want to go down the dark route of making it compatible on more browsers you need to fetch the file via ajax, create a blob, create a url from the blob, create an anchor element and assign the blob url, then trigger a click on it.
Or as #Quentin says if cross-origin is blocked then I would prefer to proxy to the file via your server on the same domain and still use the download attribute href="/api/fileproxy?url=http://....".
use window.open(fileUrl) - will download ;
Do like this,
<a href={fileUrl}><button>Download</button></a>
Okay to be precise you can follow below steps (this is in java)
1. Write new api which reads file into ByteArrayOutputStream and set the proper response type (File name and path will be requsted by Client)
Eg :
ByteArrayOutputStream baos = dao.readFIle(filename, filepath);
String filename = filename+"."+fileextension;
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
response.setContentType("application/zip");
response.getOutputStream().write(baos.toByteArray());
response.flushBuffer();
baos.close();
Call that api form client by sending filename and path as attributes
I have a list of bills in my table and each row has it's own unique bill (different date, amount etc...). I have successfully managed to make php call via Soap:Wrapper in Laravel 5 and when i type in browser "path to that procedure" i get my pdf. But i would like to open it using Javascript.
My code of server side
$pdfData= $soap->racun($data);
header("Content-type: application/pdf");
header("Content-Length:" . strlen($pdfData));
//this line if i want to preview my pdf in browser
header("Content-Disposition: inline; filename=pdf.pdf");
//this line if i want to download my pdf
header('Content-Disposition: attachment; filename="pdf.pdf"');
print $pdfData;
My code of client side is
$.ajax({
type:"GET",
url:"/path",
data:"param1=" + par1+"¶m2="+ par2+ "¶m3="+par3,
success:function(msg){
//alert(msg);
//here needs to show that pdf but don't know how
document.write(msg);
},
fail:function(){
alert('Error with pdf');
}
});
So when a user click on a link to get his bill i send AJAX call and get that pdf using SOAP WebService. The problem is that i can preview it or download it if i write /path in my browser, but don't know how to do it inside Javascript. What am i doing wrong?
Well, you're sending a GET request, so you can simply do this:
window.location = "/path?" + "param1=" + par1+ "¶m2=" + par2 + "¶m3=" + par3;
You might also want to check this answer.
I'm working on codebeautify.org site,
in which I want to convert excel to HTML file. I've converted that but I can't download the file.
public function convertHTML(){
$fileName=$this->input->post('fileName');
$file_ext = end(explode('.',$fileName));
if($file_ext!="xlsx"){
$data = new Spreadsheet_Excel_Reader(LOCAL_UPLOAD_PATH.$fileName);
for($s=0; $s<count($data->sheets); $s++) {
echo "<b><u>Sheet Name</u> :- ".$data->boundsheets[$s]['name']."</b><hr>";
echo $data->dump(false,false,$s);
echo "<hr>";
}
$fh = fopen(LOCAL_UPLOAD_PATH.$fileName, 'a');
fclose($fh);
unlink(LOCAL_UPLOAD_PATH.$fileName);
}
else{
$this->convertXLSXtoHTML($fileName);
}
}
Now I want to download it. How can I do it?
If you want to download instead of Show in the browser there are some options, but to be honest, I prefer show the file, because the options are not a very good user experience, and the last one not always is possible:
Option 1: Insert the excel in a .zip
Option 2: The browser (some of them) has an option which ask to the users if they want to show or download the file, the problem with this is that option is not working only in your page.
Option 3: add in the .htacces the next code to force the browser to download some type of files:
<FilesMatch "\.(?i:xlxs)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
I want to open a file (format could vary between things like .docx, .pdf and .jpg) in a new window when someone clicks on a button. However, the URL where the file is located can return either the file, when I use the header {"Accept" : "application/octet-stream"}, or it can return a JSON file with data when using the header {"Accept" : "application/json"}.
When I do
window.open(myUrl);
I cannot specify if I get my octet-stream or json. How can I add my header, or otherwise ensure that I get the proper file?
I'd like to create an email from a Javascript web application. I'm completely aware of the many SO questions on this (e.g. Open Outlook HTML with Chrome). There are problems with the typical answers:
Mailto: link: This will let you create an email, but only in plain text (no HTML) and it does not allow for attachments.
Activex: IE only, my application needs to run in Firefox and Chrome too. FF & Chrome plug-ins to allow ActiveX are security hazards and seem to be buggy.
Server-side sends via SMTP: The email does not end up in the "Sent" folder for the user. Plus hurdles letting the user edit HTML in the browser and attach files.
Create an Outlook .MSG file: There seem to be no libraries and little written about doing this. Apparently the file format actually has an entire FAT file storage system embedded.
Key differences between many other SO questions and mine:
I do have access to the client machines, so I could install
helper applications or add-ins, change settings as needed, etc.
The interface does not need to actually send the mail, it only needs
to set it up for the user.
I also need to be able to give the email an attachment from JS (e.g. a PDF).
I cannot be the first web app developer to face this and yet I'm unable to find a solution either commercial or open source.
Update:
I used the EML file method and it works well so far. Here's my JS code to create and trigger it:
var emlContent = "data:message/rfc822 eml;charset=utf-8,";
emlContent += 'To: '+emailTo+'\n';
emlContent += 'Subject: '+emailSubject+'\n';
emlContent += 'X-Unsent: 1'+'\n';
emlContent += 'Content-Type: text/html'+'\n';
emlContent += ''+'\n';
emlContent += htmlDocument;
var encodedUri = encodeURI(emlContent); //encode spaces etc like a url
var a = document.createElement('a'); //make a link in document
var linkText = document.createTextNode("fileLink");
a.appendChild(linkText);
a.href = encodedUri;
a.id = 'fileLink';
a.download = 'filename.eml';
a.style = "display:none;"; //hidden link
document.body.appendChild(a);
document.getElementById('fileLink').click(); //click the link
MSG file format is documented, but it is certainly not fun...
Why not create an EML (MIME) file?
The suggestion is to use the EML (MIME) format. According to the OP, they considered the MSG file format (#4), but were discouraged by its complexity and lack of JS libraries that process that format. If MSG file was considered, MIME is a much better choice - it is text based, so no special libraries are required to create it. Outlook will be able to open it just as easily as an MSG file.
To make sure EML message is treated as an unsent message by Outlook, set the X-Unsent MIME header to 1.
The simplest EML file would look like the following:
To: Joe The User <joe#domain.demo>
Subject: Test EML message
X-Unsent: 1
Content-Type: text/html
<html>
<body>
Test message with <b>bold</b> text.
</body>
</html>
Using the idea of plain text eml files, I came up with this: http://jsfiddle.net/CalvT/un3hapej/
This is an edit of something I found - to create a .txt file then download it. As .eml files are practically .txt files, I figured this would work. And it does. I've left the textarea with the sample email in so you can easily test. When you click on create file, it then gives you a download link to download your .eml file. The only hurdle I can see is making the browser open the .eml file after it has been downloaded.
EDIT: And thinking about it, as you have access to the client machines, you could set the browser to always open files of that type. For instance in Chrome, you can click on the arrow beside the download and select always open files of this type.
Here's the code
HTML:
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
<textarea id="textbox" style="width: 300px; height: 200px;">
To: User <user#domain.demo>
Subject: Subject
X-Unsent: 1
Content-Type: text/html
<html>
<body>
Test message
</body>
</html>
</textarea>
<button id="create">Create file</button>
<a download="message.eml" id="downloadlink" style="display: none">Download</a>
Nobody seems to have answered the attachment question, so here's my solution:
create the EML as a multipart/mixed message.
Content-Type: multipart/mixed; boundary=--boundary_text_string
With this, you can have multiple parts in your email.
Multiple parts let you add attachments, like this.
Content-Type: application/octet-stream; name=demo.pdf
Content-Transfer-Encoding: base64
Content-Disposition: attachment
Start with your email headers, then add your boundary, then the part contents (newline locations are very important, clients won't parse your file correctly otherwise). You can add multiple parts. Below is an example. Note that the last boundary is different from the others (2 dashes at the end).
To: Demo-Recipient <demo#demo.example.com>
Subject: EML with attachments
X-Unsent: 1
Content-Type: multipart/mixed; boundary=--boundary_text_string
----boundary_text_string
Content-Type: text/html; charset=UTF-8
<html>
<body>
<p>Example</p>
</body>
</html>
----boundary_text_string
Content-Type: application/octet-stream; name=demo.txt
Content-Transfer-Encoding: base64
Content-Disposition: attachment
ZXhhbXBsZQ==
----boundary_text_string
Content-Type: application/octet-stream; name=demo.log
Content-Transfer-Encoding: base64
Content-Disposition: attachment
ZXhhbXBsZQ==
----boundary_text_string--
This gives you a eml file with two attachments.
See RFC 1371 if you want to know more specifics on how this works.
I had encoding problem when creating an .eml file with non-english characters and then opening it in Outlook.
The problem was that I put the "charset=" to the wrong place and did not put the quotes (") around the encoding.
The solution:
function createShiftReportEmail() {
const title = "Shift Összefoglaló";
const body = "ÁÉŐÚŰÓÜÖÍűáéúőóöí";
const emlContent = new Blob([`data:message/rfc822 eml,\nSubject: ${title}\nX-Unsent: 1\nContent-Type: text/plain;charset="utf-8"\n\n${body}`]);
if (!document.querySelector('#downloadEmail')) {
document.body.insertAdjacentHTML('beforeend', '<a id="downloadEmail" download="ShiftReport.eml" style="display: none">Download</a>');
}
const downloadBtn = document.querySelector('#downloadEmail');
downloadBtn.href = URL.createObjectURL(emlContent);
downloadBtn.click();
}
Edit: Turns out quotes (") are not even necessary. Only the placement was wrong for me.