文件下載(使用springmvc框架中ResponseEntity對象)


package com.atguigu.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.servlet.http.HttpSession;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UploadAndDown {
    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpSession session) throws Exception{
        //獲取下載文件的路徑 (獲取tomcat服務器的位置)
        String realPath = session.getServletContext().getRealPath("img");
        String finalPath = realPath+ File.separator +"1.jpg";
        //創建字節輸入流
        InputStream in = new FileInputStream(finalPath);
        //available():獲取輸入流所讀取的文件的最大字節數
        byte[] body = new byte[in.available()];
        //把字節讀取到數組中
        in.read(body);
        //設置請求頭
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=aaa.jpg");
        //設置響應狀態
        HttpStatus statusCode = HttpStatus.OK;
        in.close();

        
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
        
    }

}

 


免責聲明!

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



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