1.pom.xml加入: <!-- https://mvnrepository.com/artifact/com.googlecode.juniversalchardet/juniversalchardet --> <dependency> <groupId>com.googlecode.juniversalchardet</groupId> <artifactId>juniversalchardet</artifactId> <version>1.0.3</version> </dependency>
2. 工具類
class GetByteEncode {
String getEncoding(byte[] bytes) {
String deafultCode = "UTF-8";
UniversalDetector detector = new UniversalDetector(null);
detector.handleData(bytes, 0, bytes.length);
detector.dataEnd();
String encoding = detector.getDetectedCharset();
detector.reset();
if (encoding == null) {
encoding = deafultCode;
}
return encoding;
}
}
3.使用:
String filenameIso = new String(data.getFileName().getBytes("UTF-8"), "iso-8859-1");
/* 設置文件名 */
response.addHeader("Content-Disposition", "fileName=\"" + filenameIso + "\"");
os = response.getOutputStream();
byte[] b = fileInfo.getData().getFileByte();
String encoding = new GetByteEncode().getEncoding(b); //編碼判斷 --動態
response.setHeader("Content-type", "text/html;charset=" + encoding);
String a = new String(fileInfo.getData().getFileByte(), encoding);
os.write(a.getBytes(encoding));