How to encode the filename parameter of Content-Disposition header in HTTP?

前端 未结 18 1782
北荒
北荒 2020-11-21 06:15

Web applications that want to force a resource to be downloaded rather than directly rendered in a Web browser issue a Content-Disposition hea

18条回答
  •  情话喂你
    2020-11-21 07:10

    I use the following code snippets for encoding (assuming fileName contains the filename and extension of the file, i.e.: test.txt):


    PHP:

    if ( strpos ( $_SERVER [ 'HTTP_USER_AGENT' ], "MSIE" ) > 0 )
    {
         header ( 'Content-Disposition: attachment; filename="' . rawurlencode ( $fileName ) . '"' );
    }
    else
    {
         header( 'Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode ( $fileName ) );
    }
    

    Java:

    fileName = request.getHeader ( "user-agent" ).contains ( "MSIE" ) ? URLEncoder.encode ( fileName, "utf-8") : MimeUtility.encodeWord ( fileName );
    response.setHeader ( "Content-disposition", "attachment; filename=\"" + fileName + "\"");
    

提交回复
热议问题