Java實(shí)現(xiàn)下載文件的6種方式
一、以流的方式下載
public HttpServletResponse download(String path, HttpServletResponse response) {
? ? ? ? try {
? ? ? ? ? ? // path是指欲下載的文件的路徑。
? ? ? ? ? ? File file = new File(path);
? ? ? ? ? ? // 取得文件名。
? ? ? ? ? ? String filename = file.getName();
? ? ? ? ? ? // 取得文件的后綴名。
? ? ? ? ? ? String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
? ? ? ? ? ? // 以流的形式下載文件。
? ? ? ? ? ? InputStream fis = new BufferedInputStream(new FileInputStream(path));
? ? ? ? ? ? byte[] buffer = new byte[fis.available()];
? ? ? ? ? ? fis.read(buffer);
? ? ? ? ? ? fis.close();
? ? ? ? ? ? // 清空response
? ? ? ? ? ? response.reset();
? ? ? ? ? ? // 設(shè)置response的Header
? ? ? ? ? ? response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
? ? ? ? ? ? response.addHeader("Content-Length", "" + file.length());
? ? ? ? ? ? OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
? ? ? ? ? ? response.setContentType("application/octet-stream");
? ? ? ? ? ? toClient.write(buffer);
? ? ? ? ? ? toClient.flush();
? ? ? ? ? ? toClient.close();
? ? ? ? } catch (IOException ex) {
? ? ? ? ? ? ex.printStackTrace();
? ? ? ? }
? ? ? ? return response;
? ? }二、下載本地文件
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
? ? ? ? // 下載本地文件
? ? ? ? String fileName = "Operator.doc".toString(); // 文件的默認(rèn)保存名
? ? ? ? // 讀到流中
? ? ? ? InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路徑
? ? ? ? // 設(shè)置輸出的格式
? ? ? ? response.reset();
? ? ? ? response.setContentType("bin");
? ? ? ? response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
? ? ? ? // 循環(huán)取出流中的數(shù)據(jù)
? ? ? ? byte[] b = new byte[100];
? ? ? ? int len;
? ? ? ? try {
? ? ? ? ? ? while ((len = inStream.read(b)) > 0)
? ? ? ? ? ? ? ? response.getOutputStream().write(b, 0, len);
? ? ? ? ? ? inStream.close();
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }三、下載網(wǎng)絡(luò)文件
public void downloadNet(HttpServletResponse response) throws MalformedURLException {
? ? ? ? // 下載網(wǎng)絡(luò)文件
? ? ? ? int bytesum = 0;
? ? ? ? int byteread = 0;
? ? ? ? URL url = new URL("windine.blogdriver.com/logo.gif");
? ? ? ? try {
? ? ? ? ? ? URLConnection conn = url.openConnection();
? ? ? ? ? ? InputStream inStream = conn.getInputStream();
? ? ? ? ? ? FileOutputStream fs = new FileOutputStream("c:/abc.gif");
? ? ? ? ? ? byte[] buffer = new byte[1204];
? ? ? ? ? ? int length;
? ? ? ? ? ? while ((byteread = inStream.read(buffer)) != -1) {
? ? ? ? ? ? ? ? bytesum += byteread;
? ? ? ? ? ? ? ? System.out.println(bytesum);
? ? ? ? ? ? ? ? fs.write(buffer, 0, byteread);
? ? ? ? ? ? }
? ? ? ? } catch (FileNotFoundException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? } catch (IOException e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }public void downLoadFile(HttpServletResponse response, String httpUrl) {
? ? ? ? ServletOutputStream out = null;
? ? ? ? try {
? ? ? ? ? ? //與服務(wù)器建立連接
? ? ? ? ? ? URL url = new URL(httpUrl);
? ? ? ? ? ? URLConnection conn = url.openConnection();
? ? ? ? ? ? InputStream inputStream = conn.getInputStream();
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? //1.設(shè)置文件ContentType類型,這樣設(shè)置,會(huì)自動(dòng)判斷下載文件類型
? ? ? ? ? ? ? ? response.setContentType("multipart/form-data");
? ? ? ? ? ? } catch (Exception e){
? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? }
? ? ? ? ? ? out = response.getOutputStream();
? ? ? ? ? ? // 讀取文件流
? ? ? ? ? ? int len = 0;
? ? ? ? ? ? byte[] buffer = new byte[1024 * 10];
? ? ? ? ? ? while ((len = inputStream.read(buffer)) != -1) {
? ? ? ? ? ? ? ? out.write(buffer, 0, len);
? ? ? ? ? ? }
? ? ? ? ? ? out.flush();
? ? ? ? ? ? out.close();
? ? ? ? ? ? inputStream.close();
? ? ? ? } catch (Exception e){
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? }四、在線打開的方式
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
? ? ? ? File f = new File(filePath);
? ? ? ? if (!f.exists()) {
? ? ? ? ? ? response.sendError(404, "File not found!");
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
? ? ? ? byte[] buf = new byte[1024];
? ? ? ? int len = 0;
? ? ? ? response.reset(); // 非常重要
? ? ? ? if (isOnLine) { // 在線打開方式
? ? ? ? ? ? URL u = new URL("file:///" + filePath);
? ? ? ? ? ? response.setContentType(u.openConnection().getContentType());
? ? ? ? ? ? response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
? ? ? ? ? ? // 文件名應(yīng)該編碼成UTF-8
? ? ? ? } else { // 純下載方式
? ? ? ? ? ? response.setContentType("application/x-msdownload");
? ? ? ? ? ? response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
? ? ? ? }
? ? ? ? OutputStream out = response.getOutputStream();
? ? ? ? while ((len = br.read(buf)) > 0)
? ? ? ? ? ? out.write(buf, 0, len);
? ? ? ? br.close();
? ? ? ? out.close();
? ? }五、將文件轉(zhuǎn)換成base64
/**
* 將文件轉(zhuǎn)為base64
*/
public static String getBase64FromFile(File file) throws IOException {
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(file);
out = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while ((read = in.read(buffer, 0, 1024)) != -1) {
out.write(buffer, 0, read);
}
return Base64.getEncoder().encodeToString(out.toByteArray());
} catch (IOException e) {
throw e;
} finally {
if (in != null) {
in.close();
}
if (out != null){
out.close();
}
}
}六、將MultipartFile轉(zhuǎn)換為File
/**
* 將MultipartFile轉(zhuǎn)換為File
*/
public static File MultipartFileToFile(MultipartFile multiFile) throws IOException {
String fileName = multiFile.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf("."));
InputStream in = null;
OutputStream out = null;
try {
File file = File.createTempFile(fileName, prefix);
out = new FileOutputStream(file);
in = multiFile.getInputStream();
int read = 0;
byte[] buffer = new byte[1024];
while ((read = in.read(buffer, 0, 1024)) != -1) {
out.write(buffer, 0, read);
}
return file;
} catch (Exception e) {
throw e;
}finally {
if (in != null){
in.close();
}
if (out != null){
out.close();
}
}
}到此這篇關(guān)于Java實(shí)現(xiàn)下載文件的6種方式的文章就介紹到這了,更多相關(guān)Java 下載文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring boot JPA實(shí)現(xiàn)分頁(yè)和枚舉轉(zhuǎn)換代碼示例
這篇文章主要介紹了Spring boot JPA實(shí)現(xiàn)分頁(yè)和枚舉轉(zhuǎn)換代碼示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Java設(shè)計(jì)模式——工廠設(shè)計(jì)模式詳解
這篇文章主要介紹了Java設(shè)計(jì)模式——工廠設(shè)計(jì)模式詳解,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
Java實(shí)現(xiàn)PDF文件的分割與加密功能
這篇文章主要為大家分享了如何利用Java語(yǔ)言實(shí)現(xiàn)PDF文件的分割與加密以及封面圖的生成,文中的示例代碼簡(jiǎn)潔易懂,感興趣的可以了解一下2022-04-04
Flowable數(shù)據(jù)庫(kù)表分類及數(shù)據(jù)字典解析
這篇文章主要介紹了Flowable數(shù)據(jù)庫(kù)表分類及數(shù)據(jù)字典解析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
詳解Java的TCP/IP編程學(xué)習(xí)--基于定界符的成幀
這篇文章主要介紹了Java的TCP/IP編程學(xué)習(xí)--基于定界符的成幀,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
spring boot開發(fā)遇到坑之spring-boot-starter-web配置文件使用教程
Spring Boot支持容器的自動(dòng)配置,默認(rèn)是Tomcat,當(dāng)然我們也是可以進(jìn)行修改的。這篇文章給大家介紹了spring boot開發(fā)遇到坑之spring-boot-starter-web配置文件使用教程,需要的朋友參考下吧2018-01-01
Java中的ArrayList.trimToSize()方法詳解
這篇文章主要介紹了Java中的ArrayList.trimToSize()方法詳解,前幾天看了Java?ArrayList,沒(méi)有明白trimToSize()這個(gè)方法是什么意思,所以看了一下源碼并且debug一下自己的一個(gè)例子,明白了其中的含義,需要的朋友可以參考下2023-11-11

