1. 程式人生 > >springmvc 檔案下載介面

springmvc 檔案下載介面

介面服務

	@RequestMapping(value="/download")
	public ResponseEntity<?> fileDownload(HttpServletResponse response,HttpServletRequest req){
		
		String contentType = req.getContentType();
		System.out.println(contentType);
		
		try {
			HttpHeaders headers = new HttpHeaders();
			String filepath = "D:/***/eomApplication表.pdf";
			File file = new File(filepath);
			if (!file.exists()) {
				URI location = new URI(filepath);
				HttpHeaders responseHeaders = new HttpHeaders();
				responseHeaders.setLocation(location);
				responseHeaders.set("MyResponseHeader", "MyValue");
				return new ResponseEntity<String>("檔案路徑不正確!", responseHeaders, HttpStatus.NOT_FOUND);
				
			}
			String dfileName = new String(file.getName().getBytes("utf-8"), "iso8859-1");
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.setContentDispositionFormData("attachment", dfileName);
			byte[] bytes = FileUtils.readFileToByteArray(file);
			return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
		} catch (URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new ResponseEntity<String>("檔案路徑不正確!", HttpStatus.INTERNAL_SERVER_ERROR);
	}

呼叫


package demo.message;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;


/**
 * @author Liukj
 * @date 2018年5月9日
 * @Description:   
 */
public class HttpUtil {
	
	private static final Logger logger   = LoggerFactory.getLogger(HttpUtil.class);
	
	
	/**
	 * post 請求
	 * @param url
	 * @param outstr
	 * @return
	 */
	public static String doPostStr(String url,String outstr){
		HttpClient  httpClient = HttpClientBuilder.create().build();
		logger.debug("發起請求的地址: {}", url);
		HttpPost httpPost = new HttpPost(url);
		// 設定請求的header  
//		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf-8");
		
		try {
			// 設定請求的引數 
			if(outstr != null){
				StringEntity entity = new StringEntity(outstr,"UTF-8");
				entity.setContentEncoding("UTF-8");  
				entity.setContentType("application/json"); 
				httpPost.setEntity(entity);
			}
			// 執行請求
			HttpResponse execute = httpClient.execute(httpPost);
			int code = execute.getStatusLine().getStatusCode();
			
			if(code == HttpStatus.CREATED.value()){
				String fileName = getFileName(execute);// 獲取下載檔案的檔名

				System.out.println(fileName+"-----------------------------");
				byteArray = EntityUtils.toByteArray(execute.getEntity());
				String path = "D:/***";要寫入的檔案目錄
				createFile(byteArray,path,fileName);
			}
			
//			Header[] headers = execute.getHeaders("Content-Disposition");
//			for (Header header : headers) {
//				String name = header.getName();
//				String value = header.getValue();
//			}
//			JSONObject jsonObject = JSONObject.fromObject(result);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return null;
	}
	
	/** 
     * 獲取response header中Content-Disposition中的filename值 
     * @param response
     * @return 
     */
    private static String getFileName(HttpResponse response) {  
        Header contentHeader = response.getFirstHeader("Content-Disposition");  
        String filename = null;  
        if (contentHeader != null) {  
            HeaderElement[] values = contentHeader.getElements();  
            if (values.length == 1) {  
                NameValuePair param = values[0].getParameterByName("filename");  
                if (param != null) {  
                    try {
                    //此處根據具體編碼來設定
                        filename = new String(param.getValue().toString().getBytes("ISO-8859-1"), "utf-8");  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }
        return filename;  
    }
 
	
    //位元組流轉換為檔案
	private static void createFile(byte[] bfile, String filePath, String fileName)
    {
        BufferedOutputStream bos = null;
        
        FileOutputStream fos = null;
        File file = null;
        try
        {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory())
            {//判斷檔案目錄是否存在  
                dir.mkdirs();
            }
            file = new File(filePath + "\\" + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }
	
	public static void main(String[] args) {
		String doPostStr = doPostStr("http://localhost:8080/demo02/download.do", null);

		System.out.println(doPostStr);
	}
}