根据下载地址URL下载文件到本地指定目录

本文介绍了解决Ajax提交导致浏览器不弹出下载框的问题,通过使用form表单提交来触发下载对话框,并提供了两种处理方法:一是通过JS模拟form表单提交,二是代码中直接指定下载目录。

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

一、浏览器弹下载框选择目录下载:

不弹下载的提示框是因为你的提交方式是ajax提交,是不会弹出提示框的,你得换成form表单提交,就可以顺利弹框。

js模拟form表单提交可以参照我另一篇博客:https://blog.csdn.net/hskw444273663/article/details/86170641

    //材料下载处理
    public static void downloadMaterialFile(HttpServletRequest request,HttpServletResponse response,String src){
        try {
		String fileName = src.substring(src.lastIndexOf("/"));
		String fileNameEncode = URLEncoder.encode(fileName.substring(1, fileName.length()), "utf-8");
		//判断字符串中是否包含中文
		Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		Matcher m = p.matcher(src);
		if (m.find()) {
		   src = src.replace(fileName.substring(1, fileName.length()), fileNameEncode);
		}

		URL url_upload = new URL(src);
		HttpURLConnection conn = (HttpURLConnection) url_upload.openConnection();
		//设置超时间为3秒
		conn.setConnectTimeout(3*1000);
		//防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0?(compatible;?MSIE?5.0;?Windows?NT;?DigExt)");
		conn.setRequestProperty("Accept-Charset", "utf-8");
		conn.setRequestMethod("GET");
		//得到输入流
		InputStream inputStream = conn.getInputStream();
		//获取自己数组
		byte[] getData = readInputStream(inputStream);
		response.reset();//OutputStream和Writer在一个response中不能同时获得
		// 以流的形式下载文件
		response.setContentType("multipart/form-data");
		OutputStream toClient = null;
		// 设置相应头,控制浏览器下载该文件,这里就是会出现当你点击下载后,出现的下载地址框
		response.setHeader("Content-Disposition", "attachment;filename=\""
					+ new String(fileName.getBytes("gb2312"), "ISO8859-1") + "\"");
		toClient = new BufferedOutputStream(response.getOutputStream());
		toClient.write(getData);
		toClient.flush();
		toClient.close();
	    } catch (UnsupportedEncodingException e2) {
		    e2.printStackTrace();
	    } catch (IOException e) {
		    e.printStackTrace();
	    }
        
   }
				
    //将输入流转换成二进制文件流
    public static byte[] readInputStream(InputStream inputStream) throws IOException{
	    BufferedInputStream reader = null;
	    reader =  new BufferedInputStream(inputStream);
        List<Integer> list = new ArrayList<Integer>();
        int a = 0;
        while((a = reader.read()) != -1){
             list.add(a);
        }
        byte[] content = new byte[list.size()];
        for(int index = 0 ; index < list.size() ; index ++){
             content[index] = list.get(index).byteValue();
        }
        return content;
    }

二、浏览器不弹下载框,代码中指定下载目录:

public boolean createTemplateFile(HttpServletRequest request, HttpServletResponse response) throws IOException{
		boolean flag = false;
		String src = request.getParameter("fileUrl");
		FileOutputStream fos = null;
		String craetePath ="upload/meterial";
		String pathRoot=request.getSession().getServletContext().getRealPath("");

		File file=new File(pathRoot+"/"+craetePath);  
		if(!file.exists()) {    
		    file.mkdirs();    
		} 
		//材料下载处理
		try {
			String fileName = src.substring(src.lastIndexOf("/"));
			String fileNameEncode = URLEncoder.encode(fileName.substring(1, fileName.length()), "utf-8");
			//判断字符串中是否包含中文
		    Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
		    Matcher m = p.matcher(src);
		    if (m.find()) {
		    	src = src.replace(fileName.substring(1, fileName.length()), fileNameEncode);
		    }

			URL url_upload = new URL(src);
			HttpURLConnection conn = (HttpURLConnection) url_upload.openConnection();
			//设置超时间为3秒
			conn.setConnectTimeout(3*1000);
			//防止屏蔽程序抓取而返回403错误
			conn.setRequestProperty("User-Agent", "Mozilla/4.0?(compatible;?MSIE?5.0;?Windows?NT;?DigExt)");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestMethod("GET");
			response.reset();//OutputStream和Writer在一个response中不能同时获得
			//得到输入流
			InputStream inputStream = conn.getInputStream();
			fos = new FileOutputStream(pathRoot +"/"+ craetePath + fileName);

			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inputStream.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			fos.flush();
			inputStream.close();
			fos.close();
			flag = true;
			return flag; 
		} catch (UnsupportedEncodingException e2) {
			e2.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值