java获取远程文件服务器文件保证文件名上传下载一样 http协议

@Controller
@RequestMapping(value = "/")
public class TestController extends BaseController{

	//文件服务器链接
	@Value("http://hanjq.com/uploadapi")
	private String fileServerURL;

	@RequestMapping("/downloadReFileName/{orderId}")
	@Scope(value="prototype")
	public void updateUploadStatus(HttpServletRequest request, HttpServletResponse response, @PathVariable @NotNull String orderId) throws IOException {
		//此处说明 order对象是系统订单对象,order表中存了文件编码之后的路径跟原始的文件名,重命名之后下载保证上传跟下来的文件名称不变! 例:/downLoad/htwins1/M00/00/07/wKgDwF8jozyAWqH0AAC2ADDlg_k681.doc    会议记录word.doc
		Order order = new Order();
		order.setOrderId(Long.valueOf(orderId));
		order = orderService1.getOrder(order);
		if(null != order){
			String fileName = order.getInvoiceFileName();//文件名带格式
			String filePath = fileServerURL+order.getInvoiceUrl();//downLoad/htwins1/M00/00/07/wKgDwF8jozyAWqH0AAC2ADDlg_k681.do
			URLConnection con = null;
			BufferedReader br = null;
			BufferedOutputStream bos = null;
			BufferedInputStream bis = null;
			URL url;
			try {
				//请求文件流
				url = new URL(filePath);
				con = url.openConnection();
				con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				con.connect();
				// 获取文件流
				bis=new BufferedInputStream(con.getInputStream());
				//清空response
				response.reset();
				//头部设置文件类型
				response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
				response.addHeader("Content-Length","" +con.getContentLength());
				response.setContentType("application/octet-stream");
				bos = new BufferedOutputStream(response.getOutputStream());
				//设置文件大小
				byte buf[] = new byte[10*1024];
				int len = -1;
				//写入
				while ((len = bis.read(buf,0,10240)) != -1) {
					bos.write(buf, 0, len);
					bos.flush();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			} finally {
				if (bos != null) {
					try {
						bos.close();
					} catch (IOException e) {
						throw new RuntimeException(e);
					} finally {
					}
				}
				if(bis!=null){
					bis.close();
				}
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
						throw new RuntimeException(e);
					} finally {
					}
				}
			}
		}
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值