SpringBoot環境下java實現文件的下載


思路:文件下載,就是給服務器上的文件創建輸入流,客戶端創建輸出流,將文件讀出,讀入到客戶端的輸出流中,(流與流的轉換)

package com.cst.icode.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cst.util.file.Files;
import com.cst.util.file.Files.CstDir;


@RestController
@RequestMapping("/file")
public class TestController {
	
	@GetMapping("/froalar/get/{path}")
	public Object getFroalarFile(@PathVariable String path,HttpServletResponse re) {
		path=path.replace(":", File.separator);
		// 平台的下載文件根路徑
		File uploadRoot = Files.getDir(CstDir.upload);//=后面是要獲得下載的文件的路徑
		File downloadDir = new File(uploadRoot,  File.separator+path);
		return downloadFile(downloadDir,re);
	}
	private OutputStream downloadFile(File file,HttpServletResponse re) {
		if (file.exists()) {
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                OutputStream os = re.getOutputStream();
                while (i != -1) {
                	os.write(buffer,0,i);
                    i = bis.read(buffer);
                }
                return os;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
		return null;
	}

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM