- 前提:整一下文件下载,之前的文件下载不是通过字符串的形式返回给前端的,而是直接放在响应中让浏览器来处理,前端不处理,但是存在很多前端问题所以就没法弄了。所以就换成字符流的形式了,虽然做完了但是还是有点不太懂交互所以呢就整一下这个,话不多说开弄。
- 方式a:最常见的base64的字符串流,前端的话需要调用atob方法即可。
File url1 = new File(url);
String name = url1.getName();
int i = name.lastIndexOf(".");
String fileType = name.substring(i + 1);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("fileType", fileType);
InputStream in = null;
try {
in = new FileInputStream(url);
byte[] data = new byte[in.available()];
in.read(data);
in.close();
jsonObject.put("file", new BASE64Encoder().encode(data));
} catch (Exception e) {
e.printStackTrace();
}
return CommonUtils.succssonJson(jsonObject);
或者
File url1 = new File(url);
String name = url1.getName();
int i = name.lastIndexOf(".");
String fileType = name.substring(i + 1);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("fileType", fileType);
InputStream in = null;
try {
byte[] data = FileUtils.readFileToByteArray(url1);
jsonObject.put("file",Base64Utils.encodeToString(data));
} catch (IOException e) {
e.printStackTrace();
}
return CommonUtils.succssonJson(jsonObject);
对应前端需要atob来处理
downloadFile(bstr , fileName,type) {
var res= window.atob(bstr)
let n=res.length
let u8arr = new Uint8Array(n)
while(n--){
u8arr[n]=res.charCodeAt(n)
}
let blob=new Blob([u8arr],{type:type})
if(window.navigator && window.navigator.msSaveOrOpenBlob){
window.navigator.msSaveOrOpenBlob(blob,fileName)
}else{
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
}
}
方式b:char的流前端直接用即可,相当于生成atob之后字符串
File url1 = new File(url);
String name = url1.getName();
int i = name.lastIndexOf(".");
String fileType = name.substring(i + 1);
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
jsonObject.put("fileType", fileType);
InputStream in = null;
try {
byte[] data = FileUtils.readFileToByteArray(url1);
StringBuffer stringBuffer = new StringBuffer();
for (int j = 0; j <data.length ; j++) {
stringBuffer.append((char)data[j]);
}
jsonObject.put("file",new String(stringBuffer));
} catch (Exception e) {
e.printStackTrace();
}
return CommonUtils.succssonJson(jsonObject);
对应的前端实现
downloadFile(res, fileName,type) {
let n=res.length
let u8arr = new Uint8Array(n)
while(n--){
u8arr[n]=res.charCodeAt(n)
}
let blob=new Blob([u8arr],{type:type})
if(window.navigator && window.navigator.msSaveOrOpenBlob){
window.navigator.msSaveOrOpenBlob(blob,fileName)
}else{
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
window.URL.revokeObjectURL(link.href)
}
}
经过测试两种方法均可处理,base64安全但多了一步操作。自己斟酌即可。