admin管理员组文章数量:1606954
使用Response实现下载文件,浏览器并没有弹出文件保存框
文件下载类是这样的:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
/**
* 文件上传下载工具
* @author jwj
*/
public class FileUtil {
/**
* 远程文件下载
* @param filePath 远程文件的url
* @param response
*/
public static void remoteFileDownload(String filePath,HttpServletResponse response) {
OutputStream outputStream = null;
InputStream inputStream = null;
URL url;
try {
url = new URL(filePath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
conn.setDoInput(true);
conn.connect();
int contentLength = conn.getContentLength();
inputStream = conn.getInputStream();
// 写明要下载的文件的大小
response.setContentLength(contentLength);
response.setHeader("Content-Disposition", "attachment;filename="+ filePath);// 设置在下载框默认显示的文件名
response.setContentType("application/octet-stream");// 指明response的返回对象是文件流
outputStream = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while((len = inputStream.read(buf))!=-1) {
outputStream.write(buf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(outputStream !=null) {
outputStream.close();
}
if(inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用的地址访问是可以出现下载的,但是在js中用ajax做请求时,返回的request headers都正常,但就是不出现下载;
最后得知:js的ajax函数的返回类型只有xml、text、json、html等类型,没有“流”类型,所以我们要实现ajax下载,不能够使用相应的ajax函数进行文件下载。但可以用js生成一个form,==用这个form提交参数,并返回“流”类型的数据。==在实现过程中,页面也没有进行刷新。
版权声明:本文标题:使用Response实现下载文件,浏览器并没有弹出文件保存框 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1726115213a1056019.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论