java读取本地图片和下载可选择路径保存图片

本文深入探讨了如何在Web应用中实现本地图片的读取、显示及服务器图片的下载功能,包括通过前台代码实现图片展示,以及提供两种下载图片的方法,一种是在服务器上直接下载,另一种是通过HTTP形式下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   1. 读取本地图片
   前台 <img src="<%=path%>xx! showPicture " />
 /**
	 * 读取本地图片,并显示
	 */
	public void showPicture(){
		LOG.info("<==StudentHisAction.toSumSetUser==>");
		super.setHttpServlet();
		if(StringUtils.isNotEmpty(picPath)){
			picPath =picPath.replace("/", File.separator);
			FileInputStream is = null;
			try {
				is = new FileInputStream(picPath);
				int size = is.available(); //文件大小
				byte[] data = new byte[size];
				is.read(data);
				is.close();
				super.getResponse().setContentType("image/*");
				OutputStream os = super.getResponse().getOutputStream(); //响应输出流
				os.write(data);
				os.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


2.下载可选择路径保存图片(服务器)
 /**
	 * 用途:下载服务器图片
	 */
	public void downPic(){
		LOG.info("<==StudentHisAction.downPic==>");
		super.setHttpServlet();
        InputStream fis = null;
        OutputStream toClient  = null;
		 try {
			 if(!StringUtils.isNotEmpty(picPath)) return;
	            // path是指欲下载的文件的路径。
	            File file = new File(picPath);
	            // 取得文件名。
	            String filename = file.getName();
	            // 以流的形式下载文件。
	            fis = new BufferedInputStream(new FileInputStream(picPath));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	           // fis.close();
	            // 清空response
	            super.getResponse().reset();
	            // 设置response的Header
	            super.getResponse().addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
	            super.getResponse().addHeader("Content-Length", "" + file.length());
	            toClient = new BufferedOutputStream(response.getOutputStream());
	            super.getResponse().setContentType("application/octet-stream");
	            toClient.write(buffer);
	            toClient.flush();
	            //toClient.close();
	        } catch (IOException ex) {
	            ex.printStackTrace();
	        }finally{
                if( fis !=null){
                   try{
                       fis.close();
                       toClient.close();
                   }catch (IOException ex) {
	                 ex.printStackTrace();
	               }
                }
            }
	}


3.下载http形式图片
/**
	 * 下载服务器图片(http形式下载)
	 */
	public void downPicByHttp(){
		LOG.info("<==StudentHisAction.downPicByHttp==>");
		super.setHttpServlet();
		if(StringUtils.isEmpty(picPath)) return;
		InputStream is = null;
		OutputStream os = null;
		HttpURLConnection httpURLConnection = null;
		try{
			picPath =picPath.replaceAll("\\\\", "/");
			File file = new File(picPath);
			String fileName = file.getName();
            super.getResponse().reset(); // 清空response
			super.getResponse().setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes())); // 设置response的Header
			super.getResponse().setContentType("application/octet-stream");
			URL url = new URL(picPath);
			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(5000);//设置网络连接超时时间
			httpURLConnection.setDoInput(true);//设置应用程序要从网络连接读取数据
			httpURLConnection.setRequestMethod("GET");//设置方式
			int responseCode = httpURLConnection.getResponseCode();//获取相应code
			if(responseCode==200){
				is = httpURLConnection.getInputStream();//从服务器返回一个输入流
				os = new java.io.BufferedOutputStream(super.getResponse().getOutputStream());
				byte[] buffer = new byte[httpURLConnection.getContentLength()];
				int len ;
				while((len=is.read(buffer,0, buffer.length))!=-1){
					os.write(buffer, 0, len);
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("下载图片失败:"+e.getMessage());
		}finally{
			try {
				is.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值