文件上傳是很簡單的解決了,可文件下載可真是難到我了。
在開發過的前后端分離項目中,有開發過angular4 版本的文件下載功能,使用文件流 blob
的方式下載文件是沒有問題的,可是在vue + axios
的版本是死活下載不了,blob
二進制數據當做字符串進行了處理。返回 response
如下:
1537363236(1).jpg
查看angualr4 版本的文件下載,同一個文件,下載的內容是一樣的,但angualr4 版本的文件下載,response
自動處理成了blob
對象;
先展示下angualr版本
文件下載的前后端代碼:
angular版本前端代碼:
//文件下載
public download(docFile){
let docIds : string[]=[];
docIds.push(docFile.docId);
this.http.doGet({
url:'/doc/docs',
search:{
"attachId": this.attachId,
"docIds" : docIds
},
responseType : ResponseContentType.Blob,
success:(req,res) =>{
let fileName = docFile.docName
if(window.navigator.msSaveOrOpenBlob){
// 兼容ie11
var blobObject = new Blob([res.result]);
window.navigator.msSaveOrOpenBlob(blobObject, fileName);
}else{
let url = URL.createObjectURL(new Blob([res.result]));
let a = document.createElement('a');
document.body.appendChild(a); //此處增加了將創建的添加到body當中
a.href = url;
a.download = fileName;
a.target = '_blank';
a.click();
a.remove(); //將a標簽移除
}
}
})
}
angular版本后端代碼:
/**
* @throws Exception @Description: 1、前端界面必須轉入attachId
* 2、根據附件編號進行下載,下載與附件有關的文件(將附件有關的多個附件打包壓縮進行下載處理) @param attachId:
* 1、不為空,且docIds有值,則下載附件對應的文檔(可能多個)進行壓紋后傳到前端 2、 如果docIds沒有值,則下載附件所有的文檔 docIds:
* 1、如果attachId為空,此值必須有值,此值也為空,則異常 2、 如果attachId為空時, 此值如果是一個文檔id,則直接下載 3、
* 如果是多個文檔ID,則會根據文檔ID下載對應的文件,并壓縮返回給前臺 @return 輸出流到前臺 @throws
*/
@GetMapping("/docs")
public ResponseEntity<byte[]> download(String attachId, String[] docIds, RedirectAttributes attr) throws Exception {
DataParamBean fileBean = docManagerService.sDownLoadFile(attachId, docIds);
HttpHeaders headers = getHeader(fileBean.getFileName());
try {
System.err.println(fileBean.getFile().toString());
//Tool.FILE.forceDelete(fileBean.getFile());
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(fileBean.getFile()), headers, HttpStatus.OK);
} catch (Exception e) {
attr.addAttribute("msgInfo", e.getMessage());
}
return null;
}
返回debugger response
內容如下:
angular.jpg
angular http
處理后如下:
before.jpg
上圖可以看出,angular http 處理后,response 的內容直接轉換成了
blob
對象
再次debugger
axios 的response 如下圖:直接當做字符串處理了,感覺像是亂碼
axios.jpg
經過不斷的調試,最終選擇了另一種方式進行文件下載。使用iframe,汗... 不是很優雅,先解決緊急問題,后期在調試和優化查找解決方案:
2018-12-12 更新,使用node 和 xhr 調試 文件上傳和下載
在這篇文章中,調試使用原生的xhr 調試發現,xhr.responseType = "blob";
屬性設置后,瀏覽器就處理了返回數據,把流處理成了blob
對象,前端不用再處理返回數據,也不用轉換數據為流數據。
步驟1:在index.html
文件新建iframe標簽
iframe.jpg
步驟2:在vue methos 中添加函數, 使用form
進行提交 docId
文檔id 和 token
會話
downloadByPath(path, name) {
const fields = [
{
name: 'docName',
value: name,
},
{
name: 'path',
value: path
},
{
name: '_token',
value: sessionStorage.getItem('Admin-Token')
}
];
const form = document.createElement('form');
form.action = process.env.BASE_API + '/docmanager/download';
form.mehod = 'GET';
form.target = 'downloadFrame';
for (let i = 0, l = fields.length; i < l; i++) {
const field = fields[i];
const f = document.createElement('input');
f.type = 'hidden';
f.name = field.name;
f.value = field.value;
form.appendChild(f);
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
},
步驟3: 修改后端代碼
/**
* 單個附件下載功能 contrle 層
*/
@GetMapping("/download")
@AccessStrategy(value = Strategy.ANY)
public ResponseEntity<byte[]> download(String path, String docName, String _token, HttpServletResponse response) throws Exception {
boolean result = docManagerService.sDownLoadFile(path,docName,response);
if(!result) {
Throws.throwException(Codes._100002, "附件不存在");
}
return null;
}
/**
* 文件下載公共服務類 ,下載指定的文檔編號的的文檔 server 層
*/
boolean sDownLoadFile(String path,String docName,HttpServletResponse response) throws Exception{
boolean result = false;
BufferedOutputStream bos = null;
InputStream is = null;
String ftpFileName = path.substring(path.lastIndexOf("/")+1);//FTP服務器保存的文件名
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;filename="+ new String(docName.getBytes("UTF-8"), "ISO8859-1"));
try{
int reply;
ftpClient.setControlEncoding(encoding);
ftpClient.connect("127.0.0.1",21);
ftpClient.login("Administrator", "watermelon");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 獲取ftp登錄應答代碼
reply = ftpClient.getReplyCode();
// 驗證是否登陸成功
if(!FTPReply.isPositiveCompletion(reply)){
ftpClient.disconnect();
return result;
}
path = path.replace("\\", "/");
path = new String(path.getBytes(encoding),"iso-8859-1");
if(path.contains(".")){
ftpFileName = path.substring(path.lastIndexOf("/")+1);
path = path.substring(0,path.lastIndexOf("/"));
}
boolean isSuccess = ftpClient.changeWorkingDirectory(path);
if(isSuccess){
FTPFile[] fs = ftpClient.listFiles();
for(FTPFile ff : fs){
if(ff.getName().equals(ftpFileName)){
is = ftpClient.retrieveFileStream(ff.getName());
StreamUtils.copy(is, response.getOutputStream());
break;
}
}
ftpClient.logout();
result = true;
}else{
return result;
}
}catch(Exception e){
e.printStackTrace();
throw e;
}finally{
try{
if(bos != null){
bos.close();
}
if(is != null){
is.close();
}
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}catch(IOException e){
e.printStackTrace();
}
}
return result;
}