通过URL下载文件

URL url = new URL(fileRoute);//fileRoute:文件URL路径
//通过URL的openStrean方法获取URL对象所表示的自愿字节输入流
InputStream is = url.openStream();
// 设置response参数,可以打开下载页面
response.reset();
String mimeType = MimeUtil.getMIMEType(fileName);//获取Mime 类型列表 地址:http://www.w3school.com.cn/media/media_mimeref.asp

response.setContentType(""+mimeType+";charset=utf-8");//new String(fileName.getBytes("utf-8"), "ISO8859-1")之前是这个,通过放到服务器上,发现乱码,如果不乱,可能是你的tomcat,server.xml配置了URIEncoding("UTF-8"),在这里不建议这样做。做好换成URLDecoder.decode(model.getFileName(), "UTF-8")
response.setHeader("Content-Disposition","attachment;filename="+URLDecoder.decode(model.getFileName(), "UTF-8")); 
ServletOutputStream out = response.getOutputStream();
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
bis = new BufferedInputStream(is);
bos = new BufferedOutputStream(out);
byte[] e = new byte[2048];

int bytesRead;
while (-1 != (bytesRead = bis.read(e, 0, e.length))) {
bos.write(e, 0, bytesRead);
}
} catch (IOException arg24) {
throw arg24;
} finally {
if (bis != null) {
bis.close();
}

if (bos != null) {
bos.close();
}

}

return null;

转载于:https://www.cnblogs.com/hillyuen/p/7471259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现上传 Excel 文件并通过 URL 下载文件,你可以使用以下步骤: 1. 在你的服务器上创建一个目录来存储上传文件。 2. 创建一个 HTML 表单,允许用户上传 Excel 文件。你可以使用 `input type="file"` 元素来创建文件上传表单。 3. 在服务器端接收上传的文件并将其保存到上面创建的目录中。 4. 生成一个独特的 URL,可以通过该 URL 下载上传的 Excel 文件。你可以使用文件名或随机字符串来生成 URL。 5. 将生成的 URL 返回给用户,以便他们可以使用该 URL 下载文件。 下面是一个简单的示例,展示如何实现这个功能。请注意,这只是一个示例,你需要根据自己的需求进行修改。 HTML 表单: ``` <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="excel_file"> <input type="submit" value="Upload"> </form> ``` PHP 代码(upload.php): ```php <?php // 定义上传目录和 URL $upload_dir = '/path/to/upload/dir/'; $upload_url = 'http://example.com/uploads/'; // 检查是否有文件上传 if (!isset($_FILES['excel_file'])) { die('No file uploaded'); } // 将上传的文件保存到目录中 $file_name = $_FILES['excel_file']['name']; $file_path = $upload_dir . $file_name; move_uploaded_file($_FILES['excel_file']['tmp_name'], $file_path); // 生成下载 URL $download_url = $upload_url . $file_name; // 返回下载 URL 给用户 echo 'Download URL: ' . $download_url; ?> ``` 用户上传 Excel 文件后,将会保存到指定的目录中,并返回一个 URL,用户可以使用该 URL 下载文件。你可以使用类似 `http://example.com/uploads/excel_file.xlsx` 这样的 URL
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值