View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.attachment;
16  
17  import org.htmlunit.Page;
18  import org.htmlunit.WebResponse;
19  import org.htmlunit.http.ContentDisposition;
20  import org.htmlunit.http.ContentDispositionParser;
21  import org.htmlunit.util.FileUtils;
22  
23  /**
24   * An attachment represents a page received from the server which contains a
25   * {@code Content-Disposition=attachment} header.
26   *
27   * @author Bruce Chapman
28   * @author Sudhan Moghe
29   * @author Daniel Gredler
30   * @author Ronald Brill
31   * @author Lai Quang Duong
32   * @author Vidya m
33   */
34  public class Attachment {
35  
36      /** The attached page. */
37      private final Page page_;
38  
39      /** The file name of this attachment. */
40      private final String attachmentFilename_;
41  
42      /**
43       * Creates a new attachment for the specified page.
44       * @param page the attached page
45       */
46      public Attachment(final Page page) {
47          this(page, null);
48      }
49  
50      /**
51       * Creates a new attachment for the specified page.
52       * @param page the attached page
53       * @param attachmentFilename the file name of this attachment
54       */
55      public Attachment(final Page page, final String attachmentFilename) {
56          page_ = page;
57          attachmentFilename_ = attachmentFilename;
58      }
59  
60      /**
61       * Returns the attached page.
62       * @return the attached page
63       */
64      public Page getPage() {
65          return page_;
66      }
67  
68      /**
69       * Returns the file name for this attachment, the way a real browser would suggest it in
70       * its file save dialog (or use it for an automatic download).
71       *
72       * <p>If a file name was given explicitly when this attachment was created (for example because
73       * the download was triggered by an anchor with a {@code download} attribute, or the name was
74       * already derived from the response by the {@link org.htmlunit.WebClient}), this name is
75       * returned as it is. Otherwise the name is taken from the {@code Content-Disposition} header
76       * of the response of the attached page; see {@link #getSuggestedFilename(String)} for the details.</p>
77       *
78       * <p>Like a browser, this method does <em>not</em> use the URL of the request as fallback.
79       * If you need a name in this case, you have to build one on your own (for example from the
80       * URL, as the {@link DownloadingAttachmentHandler} does).</p>
81       *
82       * @return the attachment's suggested filename, or {@code null} if none was suggested
83       */
84      public String getSuggestedFilename() {
85          if (attachmentFilename_ != null) {
86              return attachmentFilename_;
87          }
88  
89          final WebResponse response = page_.getWebResponse();
90          return getSuggestedFilenameFrom(response.getContentDisposition());
91      }
92  
93      /**
94       * Returns the file name suggested by the given {@code Content-Disposition} header, or
95       * {@code null} if the header does not contain a usable file name.
96       *
97       * <p>This method does what the real browsers do when they choose the name of a downloaded
98       * file, so the result is a name that is safe to use for saving the file, and not the plain value
99       * sent by the server:</p>
100      * <ul>
101      * <li>The header is parsed by the {@link ContentDispositionParser} (RFC 6266, RFC 2183).
102      * Parameter names are case-insensitive, the value can be a token or a quoted string
103      * (with escapes), and a {@code ;} inside a quoted string does not end the value.</li>
104      * <li>The extended parameter {@code filename*} (RFC 8187, e.g. {@code filename*=UTF-8''gr%C3%B6%C3%9Fe.txt})
105      * wins over {@code filename}, whatever the order in the header is. Supported charsets are UTF-8 and
106      * ISO-8859-1; if the extended value is not usable, the plain {@code filename} is used.</li>
107      * <li>Characters that are not allowed in file names on at least one platform
108      * ({@code \ / : * ? " < > |} and control characters) are replaced by an underscore
109      * (see {@link FileUtils#sanitizeFilename(String)}). This also
110      * makes sure a path in the header can never be used to leave the download directory:
111      * {@code ../../evil.txt} becomes {@code _.._evil.txt}.</li>
112      * <li>Leading dots and white space (no hidden files) and trailing dots and white space
113      * are removed.</li>
114      * <li>If nothing is left, for example because the header has no file name or an empty one,
115      * the result is {@code null}. A browser would use the last part of the URL in this case, this has to
116      * be done by the caller.</li>
117      * </ul>
118      *
119      * <p>Not all browsers behave exactly the same in some corner cases. If the extended value uses an
120      * unknown charset, this method behaves like Chrome and Edge and ignores the extended value;
121      * Firefox decodes the value anyway. For an invalid percent encoding, Chrome and Edge keep the broken
122      * value as it is, while Firefox ignores the extended value; this method behaves like Firefox and
123      * falls back to the plain {@code filename}.</p>
124      *
125      * @param contentDispositionHeader the value of the {@code Content-Disposition} header, can be {@code null}
126      * @return the sanitized file name, or {@code null} if none was suggested
127      */
128     public static String getSuggestedFilename(final String contentDispositionHeader) {
129         return getSuggestedFilenameFrom(ContentDispositionParser.parse(contentDispositionHeader));
130     }
131 
132     /**
133      * Returns the file name suggested by the given parsed {@code Content-Disposition} header, or
134      * {@code null} if the header does not contain a usable file name.
135      * See {@link #getSuggestedFilename(String)} for the details.
136      *
137      * @param contentDisposition the parsed {@code Content-Disposition} header, can be {@code null}
138      * @return the sanitized file name, or {@code null} if none was suggested
139      * @see WebResponse#getContentDisposition()
140      */
141     public static String getSuggestedFilenameFrom(final ContentDisposition contentDisposition) {
142         if (contentDisposition == null) {
143             return null;
144         }
145 
146         // a filename* that is not usable falls back to filename
147         String filename = FileUtils.sanitizeFilename(contentDisposition.getExtendedParameter("filename"));
148         if (filename == null) {
149             filename = FileUtils.sanitizeFilename(contentDisposition.getParameter("filename"));
150         }
151         return filename;
152     }
153 }