java 读取各种类型的文件 (五)

后端java,springboot 、前端vue: 对 csv 文件的读写,以及前端预览

一、后端读

            public void readCSV() {
CSVReader reader = null;
try {
reader = new CSVReader(new InputStreamReader(new FileInputStream(xxx), "GBK"));
String[] lineData = null;
while((lineData = reader.readNext()) != null)
{
fileData.put(lineData);
}
} catch (Exception e) {
try {
reader.close();
} catch (Exception e1) {
}
LOGGER.error("读取CVS文件失败{}",e);
}
}
二、前后台配合预览
  1、controller
public ResponseEntity<byte[]> previewFile(@RequestBody FileVO fileVO) {
        if(fileVO == null || fileVO.getId() == null){
return null;
}
String filename = fileVO.getFileName();
byte[] buffer = getCSVBytes(fileVO,30);

     HttpHeaders headers = new HttpHeaders();

        //防止中文名乱码
//filename = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
try {
headers.setContentDispositionFormData("attachment", filename=java.net.URLEncoder.encode(filename, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
headers.add(HttpHeaders.CONTENT_TYPE,"application/octet-stream;charset=UTF-8");
headers.add("file-type",smsTaskFile.getFileType());
//返回
return new ResponseEntity<byte[]>(buffer, headers, HttpStatus.CREATED);
}
 private byte[] getCSVBytes(SmsTaskFile smsTaskFile, int preLines) {
byte[] fileBuffer = null;
int readLine = 0;
CSVReader reader = null;
try {
StringBuilder content = new StringBuilder("");
reader = new CSVReader(new InputStreamReader(new FileInputStream(smsTaskFile.getFilePath()), "GBK"));
String[] lineData = null;
while((lineData = reader.readNext()) != null && readLine < preLines)
{
for (String lineStr:lineData) {
content.append(lineStr).append(" ");
}
content.append("\n");
readLine++;
}
fileBuffer = content.toString().getBytes(StandardCharsets.UTF_8);
} catch (Exception e) {
try {
reader.close();
} catch (Exception e1) {
}
LOGGER.error("读取CSV文件失败{}",e);
}
return fileBuffer;
}
  2、vue
<el-button v-if="item.key == 'operate'" @click.stop="taskfilePreview(scope.row)" type="text" size="small">预览</el-button>
<el-dialog-side :visible="showPreviewFile" @close="showPreviewFile = false;fileContent=''">
  <h1>只预览文件前30行</h1><br>
<el-card>
<el-input v-if="fileContent"
v-model="fileContent"
show-word-limit
:autosize="{ minRows: 12}"
type="textarea"
></el-input>
</el-card>
</el-dialog-side>
taskfilePreview(row){
const reader = new FileReader();
  //通过readAsArrayBuffer将blob转换为ArrayBuffer对
Actions.previewFile(row).then(res => {
if (res.data) {
reader.readAsText(res.data) // 这里的res.data是blob文件流
reader.onload = (event) => {
var data = event.target.result;
this.showPreviewFile = true
this.fileContent = data
}
}
})
}
 
posted @ 2023-08-24 10:12  小魔魔  阅读(50)  评论(0编辑  收藏  举报