File name encoding problem for Spring MVC file download

Source: Internet
Author: User

When Spring mvc does file download, it encounters a filename encoding problem. After Baidu, reference the following two articles, solve the coding problem.

http://www.iefans.net/xiazai-wenjian-http-bianma-content-disposition/

https://yq.aliyun.com/articles/38945

The final code is as follows:

     PublicResponseentity<inputstreamresource>downloadFile (Path filePath)throwsfilenotfoundexception {File file=Filepath.tofile (); String MimeType=Urlconnection.guesscontenttypefromname (File.getname ()); if(MimeType = =NULL) {MimeType=Mediatype.application_octet_stream_value; } httpheaders respheaders=Newhttpheaders ();        Respheaders.set (Httpheaders.content_type, MimeType);        Respheaders.setcontentlength (File.length ()); String Encodedfilename=File.getname (); Try{encodedfilename= Urlencoder.encode (Encodedfilename, "UTF-8"); } Catch(unsupportedencodingexception e) {logger.error ("File name encoding Error!" ", E); } Respheaders.set (httpheaders.content_disposition, "attachment; Filename=\ "" + encodedfilename + "\" "+"; Filename*=utf-8 "" + encodedfilename); Inputstreamresource ISR=NewInputstreamresource (Newfileinputstream (file)); return NewResponseentity<inputstreamresource>(ISR, Respheaders, Httpstatus.ok); }

First press UTF-8 on the original file name, and then set content-disposition. Two filename is set in content-disposition to be compatible with more browsers.

File name encoding problem for Spring MVC file download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.