Java file download and export filenames garbled browser compatibility issues

Source: Internet
Author: User

Instance:

String poorname= datamap.get ("NAME"). ToString ();
String villagename = Datamap.get ("ADDRESS"). ToString ();
String filename=villagename+ "-" +poorname+ ". Doc";
Response.setcontenttype ("Application/doc");
Final String useragent = Request.getheader ("user-agent");
if (Stringutils.contains (useragent, "MSIE")) {//ie browser
filename = urlencoder.encode (filename, "UTF-8");
}else if (Stringutils.contains (useragent, "Mozilla")) {//google, Firefox browser
filename = new String (Filename.getbytes (), "iso8859-1");
}else{
filename = urlencoder.encode (filename, "UTF-8");//Other browsers
}
Response.AddHeader ("Content-disposition", "Attachment;filename="
+filename);/set up here to let the browser pop up the download prompt instead of opening it directly in the browser
Writer out = Response.getwriter ();

You can also extract the method directly for later use:

Setfiledownloadheader function is mainly based on the current user's browser, the name of the file of different encoding settings, so as to solve the different browser file name Chinese garbled problem

public static void Setfiledownloadheader (HttpServletRequest request, httpservletresponse response, String fileName) {
Final String useragent = Request.getheader ("user-agent");
try {
String finalfilename = null;
if (Stringutils.contains (useragent, "MSIE")) {//ie browser
Finalfilename = Urlencoder.encode (FileName, "UTF8");
}else if (Stringutils.contains (useragent, "Mozilla")) {//google, Firefox browser
Finalfilename = new String (Filename.getbytes (), "iso8859-1");
}else{
Finalfilename = Urlencoder.encode (FileName, "UTF8");//Other browsers
}
Response.setheader ("Content-disposition", "attachment; Filename=\ "" + finalfilename + "\" ");//Set up here to let the browser pop up the download box instead of opening it directly in the browser
} catch (Unsupportedencodingexception e) {
}
}

Java file download and export filenames garbled browser compatibility issues

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.