最近在做一個小程序 這個小程序有一個下載mp4文件的功能
但是在保存到圖冊的時候 出現錯誤提示 saveVideoToPhotosAlbum:fail invalid file type
下載接口
我寫了一個接口 以供下載文件 通過流的形式 將文件字節(jié)輸出給客戶端 代碼如下
# response對象是 HttpServletResponse類
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
try {
//文件輸入流
fileInputStream = new FileInputStream(file);
//HttpServletResponse 輸出流
outputStream = response.getOutputStream();
//構建下載文件的文件名
String disposition = "attachment;filename=" + outFileName;
response.addHeader("Content-disposition", disposition);
//邊讀 邊寫到輸出流
byte by[] = new byte[1024];
int len = -1;
while ((fileInputStream.read(by)) != -1) {
outputStream.write(by, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) fileInputStream.close();
if (outputStream != null) outputStream.close();
}
//這個寫法 文件是可以正常下載的 包括瀏覽器 下載工具 都是可以正常下載的
//但是到了小程序里面 調用saveVideoToPhotosAlbum保存視頻的時候 就會提示錯誤信息 saveVideoToPhotosAlbum:fail invalid file type
//解決方案是 加入一個響應頭 Content-Type:video/mp4
修改接口
FileInputStream fileInputStream = null;
ServletOutputStream outputStream = null;
try {
//文件輸入流
fileInputStream = new FileInputStream(file);
//Respone 輸出流
outputStream = response.getOutputStream();
//構建下載文件的文件名
String disposition = "attachment;filename=" + outFileName;
response.addHeader("Content-disposition", disposition);
//告知客戶端 這是一個視頻
response.setContentType("video/mp4");
//邊讀 邊寫到輸出流
byte by[] = new byte[1024];
int len = -1;
while ((fileInputStream.read(by)) != -1) {
outputStream.write(by, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) fileInputStream.close();
if (outputStream != null) outputStream.close();
}
#問題解決~