Browse Source

修复某些情况下txt文本乱码问题

fix-ofd
gaoxiong 4 years ago committed by kl
parent
commit
0a1ff64d18
  1. 4644
      server/src/main/java/cn/keking/service/impl/EncodingDetects.java
  2. 33
      server/src/main/java/cn/keking/service/impl/SimTextFilePreviewImpl.java

4644
server/src/main/java/cn/keking/service/impl/EncodingDetects.java

File diff suppressed because it is too large Load Diff

33
server/src/main/java/cn/keking/service/impl/SimTextFilePreviewImpl.java

@ -1,5 +1,6 @@
package cn.keking.service.impl;
import cn.keking.config.ConfigConstants;
import cn.keking.model.FileAttribute;
import cn.keking.model.ReturnResponse;
import cn.keking.service.FilePreview;
@ -11,8 +12,7 @@ import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.util.HtmlUtils;
import java.io.File;
import java.io.IOException;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
@ -27,19 +27,19 @@ public class SimTextFilePreviewImpl implements FilePreview {
public SimTextFilePreviewImpl(OtherFilePreviewImpl otherFilePreview) {
this.otherFilePreview = otherFilePreview;
}
private static final String FILE_DIR = ConfigConstants.getFileDir();
@Override
public String filePreviewHandle(String url, Model model, FileAttribute fileAttribute) {
String fileName = fileAttribute.getName();
String baseUrll = FILE_DIR + fileName;
// String suffix = fileAttribute.getSuffix();
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, fileName);
if (response.isFailure()) {
return otherFilePreview.notSupportedFile(model, fileAttribute, response.getMsg());
}
try {
File originFile = new File(response.getContent());
String charset = KkFileUtils.getFileEncode(originFile);
String fileData = FileUtil.readString(originFile, charset);
fileData = HtmlUtils.htmlEscape(fileData, StandardCharsets.UTF_8.name());
String fileData = HtmlUtils.htmlEscape(textData(baseUrll));
model.addAttribute("textData", Base64.encodeBase64String(fileData.getBytes()));
} catch (IOException e) {
return otherFilePreview.notSupportedFile(model, fileAttribute, e.getLocalizedMessage());
@ -47,4 +47,23 @@ public class SimTextFilePreviewImpl implements FilePreview {
return TXT_FILE_PREVIEW_PAGE;
}
private String textData(String baseUrll) throws IOException {
File file = new File(baseUrll);
if(!file.exists() || file.length() == 0) {
String line="";
return line;
}else {
String charset = EncodingDetects.getJavaEncode(baseUrll);
System.out.println(charset);
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(baseUrll), charset));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line).append("\r\n");
}
return result.toString();
}
}
}

Loading…
Cancel
Save