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);
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值