URL下载网络资源,中文处理

注:将中文部分使用UTF-8格式编码,再将%2F替换为/。

/**变量spectrogramPath*/
http://192.168.1.206:9000/mall/upload/brand/other/20250409/720e870c8f504fa79df88ef114674d6f/核磁图谱.pdf
/**
 * 下载图谱
 * @return
 */
public String downloadSpectrogram(){

	HttpServletResponse response = ServletActionContext.getResponse();
	OutputStream outputStream;
	InputStream inputStream;
	String fileName;
	try {
		fileName = spectrogramPath.substring(spectrogramPath.lastIndexOf("/") + 1);
		if(spectrogramPath.startsWith("http")){
			//URL url = new URL(spectrogramPath.substring(0,spectrogramPath.lastIndexOf("/") + 1) + URLEncoder.encode(fileName, "UTF-8"));
			URL url = new URL(spectrogramPath.substring(0,26) + URLEncoder.encode(spectrogramPath.substring(26), "UTF-8").replace("%2F","/"));
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
				inputStream =  urlConnection.getInputStream();
			}else {
				return printMsg("文件不存在!");
			}
		}else{
			File file = new File(com.titan.util.SystemConfig.getInstance().getProperty("NEW_FILE_PATH") + spectrogramPath);
			if(file.exists()){
				inputStream = new BufferedInputStream(new FileInputStream(file));
			}else {
				return printMsg("文件不存在!");
			}
		}
		response.reset();
		response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO8859-1"));
		response.setContentType("application/octet-stream");
		outputStream = new BufferedOutputStream(response.getOutputStream());
		int len = 0;
		while((len = inputStream.read()) != -1){
			outputStream.write(len);
		}
		outputStream.flush();
		inputStream.close();
		outputStream.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return "";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值