前兩篇寫到了oos 上傳 ,獲取訪問鏈接,那怎么下載呢。有兩種方式
第一種使用文檔里面的方法下載文件到本地,在讀取文件下載給用戶。第二種直接通過訪問鏈接進行下載。
第一種下載方式
先寫一個工具類將oos 的文件下載到本地具體代碼如下
//key 為存儲oos 的key 值 filename為下載后存儲的路徑
public static void downloadFile(String key, String filename)
throws OSSException, ClientException, IOException {
// 初始化OSSClient
OSSClient ossClient = new OSSClient(FilePath.endpoint, FilePath.accessKeyId,
FilePath.accessKeySecret);
OSSObject object = ossClient.getObject(FilePath.bucketName, key);
// 獲取ObjectMeta
ObjectMetadata meta = object.getObjectMetadata();
// 獲取Object的輸入流
InputStream objectContent = object.getObjectContent();
ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(FilePath.bucketName, key),
new File(filename));
// 關閉數據流
objectContent.close();
}
將文件下載到本能后讀取文件流下載,代碼如下:
private void downFile(HttpServletResponse response,String Path) {
try {
File file = new File(Path);
if (file.exists()) {
InputStream ins = new FileInputStream(Path);
BufferedInputStream bins = new BufferedInputStream(ins);// 放到緩沖流里面
OutputStream outs = response.getOutputStream();// 獲取文件輸出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 設置response內容的類型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(Path, "UTF-8"));// 設置頭部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 開始向網絡傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這里一定要調用flush()方法
ins.close();
bins.close();
outs.close();
bouts.close();
} else {
response.sendRedirect("../error.jsp");
}
} catch (IOException e) {
Log.error("文件下載出錯", e);
}
}
寫一個js 用來發起下載請求。傳送一個key 作為參數key 是什么請參考獲取訪問鏈接這篇文章。http://www.haha174.top/article/details/256945
$(".b_down").unbind("click").click(function(){
var form=$("<form>");//定義一個form表單
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","/download/netfile.do");
var fileInput=$("<input>");
fileInput.attr("type","hidden");
fileInput.attr("id","id");//設置屬性的名字
fileInput.attr("name","url");//設置屬性的名字
fileInput.attr("value","other/dbz_1505399510989.jpg");//設置屬性的值
$("body").append(form);//將表單放置在web中
form.append(fileInput);
form.submit();//表單提交
})
寫一個controller進行測試
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuan.boot.util.BatchDownloadAction;
@RestController
@RequestMapping("/download")
public class DownLoadController {
@RequestMapping("/netfile.do")
public void DownLoadNet(String url,HttpServletResponse response) {
new BatchDownloadAction().execute(response,url);
}
}
運行項目點擊下載按鈕出現如下圖即成功實現了
這里寫圖片描述
第二種通過訪問鏈接下載
首先先獲取訪問鏈接 具體的方法請參考http://www.haha174.top/article/details/256945
之后的到文件的輸入流 然后 向網絡傳輸文件流 完成下載具體工具類代碼如下:
//通過鏈接下載
public void DownLoadLink(HttpServletResponse response, String key) throws Exception {
String urlStr=new OSSManageUtil().getUrl(key);//(key,path);
System.out.println(urlStr);
if(StringUtils.isNotBlank(urlStr)) {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設置超時間為3秒
conn.setConnectTimeout(3*1000);
//防止屏蔽程序抓取而返回403錯誤
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到輸入流
InputStream inputStream;
inputStream = conn.getInputStream();
// InputStream ins = new FileInputStream(Path);
BufferedInputStream bins = new BufferedInputStream(inputStream);// 放到緩沖流里面
OutputStream outs = response.getOutputStream();// 獲取文件輸出IO流
BufferedOutputStream bouts = new BufferedOutputStream(outs);
response.setContentType("application/x-download");// 設置response內容的類型
response.setHeader(
"Content-disposition",
"attachment;filename="
+ URLEncoder.encode(key, "UTF-8"));// 設置頭部信息
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 開始向網絡傳輸文件流
while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
bouts.write(buffer, 0, bytesRead);
}
bouts.flush();// 這里一定要調用flush()方法
inputStream.close();
bins.close();
outs.close();
bouts.close();
} else {
response.sendRedirect("../error.jsp");
}
//this.downFile(response,path);
}
$(".b_down1").unbind("click").click(function(){
var form=$("<form>");//定義一個form表單
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","/download/netfile.do");
var fileInput=$("<input>");
fileInput.attr("type","hidden");
fileInput.attr("id","id");//設置屬性的名字
fileInput.attr("name","url");//設置屬性的名字
fileInput.attr("value","other/dbz_1505399510989.jpg");//設置屬性的值
$("body").append(form);//將表單放置在web中
form.append(fileInput);
form.submit();//表單提交
})
寫一個controller進行測試
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.yuan.boot.util.BatchDownloadAction;
@RestController
@RequestMapping("/download")
public class DownLoadController {
@RequestMapping("/netfile.do")
public void DownLoadNet(String url,HttpServletResponse response) {
new BatchDownloadAction().execute(response,url);
}
@RequestMapping("/Linkfile.do")
public void DownLoadLink(String url,HttpServletResponse response) throws Exception {
new BatchDownloadAction().DownLoadLink(response,url);
}
}
這里寫圖片描述
出現此頁面即成功
文章地址:http://www.haha174.top/article/details/251731
項目源碼 https://github.com/haha174/day