Mozilla pdf.js, How do I specify a file name to download?

I pass the address of the php file that contains the following code as a parameter to the file viewer.htmland it displays correctly, but when I click the download button in the PDF viewer, the document name is always document.pdf. This creates a problem due to how many mobile users will download files only to detect that all their files have a name document.pdfand that (for most mobile browsers) they cannot change the file name before downloading.

Should I pass any arbitrary parameter to the file or redirect to itself with the attached file name?

<?php
$content = "a binary representation of my pdf";
header("Content-type: application/pdf");
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="someFile.pdf"');
echo $content;
?>
+4
source share
1 answer

. pdf.js viewer.js:

function getPDFFileNameFromURL(url) {
  var reURI = /^(?:([^:]+:)?\/\/[^\/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/;
  //            SCHEME      HOST         1.PATH  2.QUERY   3.REF
  // Pattern to get last matching NAME.pdf
  var reFilename = /[^\/?#=]+\.pdf\b(?!.*\.pdf\b)/i;
  var splitURI = reURI.exec(url);
  var suggestedFilename = reFilename.exec(splitURI[1]) ||
                           reFilename.exec(splitURI[2]) ||
                           reFilename.exec(splitURI[3]);
  if (suggestedFilename) {
    suggestedFilename = suggestedFilename[0];
    if (suggestedFilename.indexOf('%') != -1) {
      // URL-encoded %2Fpath%2Fto%2Ffile.pdf should be file.pdf
      try {
        suggestedFilename =
          reFilename.exec(decodeURIComponent(suggestedFilename))[0];
      } catch(e) { // Possible (extremely rare) errors:
        // URIError "Malformed URI", e.g. for "%AA.pdf"
        // TypeError "null has no properties", e.g. for "%2F.pdf"
      }
    }
  }
  return suggestedFilename || 'document.pdf';
}

, majic URL- reURI regexp.

, :

http://domain.com/path/to/Named.pdf
http://domain.com/path/to/your/api?fileId=123&saveName=Named.pdf

Named.pdf regexp.

+3

Source: https://habr.com/ru/post/1546337/


All Articles