java通过url下载图片,可以另存为,不要在代码里写死下载路径,求解。。。

terrychen98 2014-10-28 09:16:10
...全文
4650 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
LC-1031 2018-11-22
  • 打赏
  • 举报
回复
感谢,正好用到了,网上都是指定路径的,我在找以流输出的
terrychen98 2014-10-29
  • 打赏
  • 举报
回复
后来我是这么解决的,希望可以帮到有需要的人
BufferedInputStream dis = null;
		BufferedOutputStream fos = null;
		
		String urlString = request.getParameter("urlString");
		String fileName = urlString.substring(urlString.lastIndexOf('/') + 1);
		
	    try {
			
	    	URL url = new URL(urlString);
	    	response.setContentType("application/x-msdownload;");  
	        response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
	        response.setHeader("Content-Length", String.valueOf(url.openConnection().getContentLength()));  
	        
	        dis = new BufferedInputStream(url.openStream());
			fos = new BufferedOutputStream(response.getOutputStream());  
			
			byte[] buff = new byte[2048];  
            int bytesRead;  
            while (-1 != (bytesRead = dis.read(buff, 0, buff.length))) {  
            	fos.write(buff, 0, bytesRead);  
            }  
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally { 
			
			if (dis != null)  
				dis.close();  
            if (fos != null)  
            	fos.close();  
            
		}
terrychen98 2014-10-28
  • 打赏
  • 举报
回复
引用 2 楼 Javainging 的回复:



		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ new String(fileName.getBytes("gb2312"), "iso8859-1"));
		
		
		String filePath =//这里是可以取到真实的物理地址的 
类似D:\tomcat\tmp123.doc 这样的路径
		InputStream in = new FileInputStream(filePath);

		OutputStream os = response.getOutputStream();

		byte[] b = new byte[1024 * 1024];
		int length;
		while ((length = in.read(b)) > 0) {
			os.write(b, 0, length);
		}
		in.close();
	}

是WEB项目 写了物理地址 点击下载时 也是下载到服务器上了 所以就想直接下载到本地 不指定物理地址 有方法不
terrychen98 2014-10-28
  • 打赏
  • 举报
回复
是的 是WEB项目 但
// 输出的文件流
    OutputStream os = new FileOutputStream(filename);
中的filename 怎么填写呢 写也不对,不写又报错,有具体的下载代码吗,可以在浏览器下载
Java_er 2014-10-28
  • 打赏
  • 举报
回复



		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ new String(fileName.getBytes("gb2312"), "iso8859-1"));
		
		
		String filePath =//这里是可以取到真实的物理地址的 
类似D:\tomcat\tmp123.doc 这样的路径
		InputStream in = new FileInputStream(filePath);

		OutputStream os = response.getOutputStream();

		byte[] b = new byte[1024 * 1024];
		int length;
		while ((length = in.read(b)) > 0) {
			os.write(b, 0, length);
		}
		in.close();
	}

  • 打赏
  • 举报
回复
如果是WEB项目、下载操作你是无法决定的;用户浏览器来决定下载操作是保存还是直接下载。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧