通过HttpURLConnection调用文件服务,实现文件下载,直接cv就能使用的文件下载。
public void downloadFile(DownloadUrl downloadUrl,HttpServletRequest request) throws IOException ,UnsupportedEncodingException{ try { URL s = new URL(request.getRequestURL().toString()); String serverAddress = s.getProtocol() + "://" + s.getHost() + ":" + s.getPort()+"/"; String url1 = downloadUrl.getUrl(); String encodedUrl = URLEncoder.encode(url1, StandardCharsets.UTF_8.toString()); String path=serverAddress+encodedUrl; //String filePath = path.replace("\\", "/"); String saveDir = "你下载到本地的地址"; File saveDirFile = new File(saveDir); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // String encode = URLEncoder.encode(filePath,"UTF-8"); //String decode = URLDecoder.decode(encode, "UTF-8"); URL url = new URL(path); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); int responseCode = httpConn.getResponseCode(); // 检查HTTP响应码 if (responseCode == HttpURLConnection.HTTP_OK) { String disposition = httpConn.getHeaderField("Content-Disposition"); String fileName = ""; if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 10, disposition.length() - 1); } } else { fileName = path.substring(path.lastIndexOf("/") + 1); } // 从URL连接获取输入流 try(InputStream inputStream = httpConn.getInputStream(); // 打开一个文件输出流 FileOutputStream outputStream = new FileOutputStream(saveDir + File.separator + fileName)) { int bytesRead; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); System.out.println("文件下载完成"); } } else { System.out.println("文件下载失败. 响应码: " + responseCode); } httpConn.disconnect(); } catch (IOException e) { e.printStackTrace(); } }
如果你的返回值不是void ,可能就会报错 同时使用了getOutputStream()和getWriter()。
如果传的文件路径是带有中文的,那么就会报错,需要进行编码;
String encode = URLEncoder.encode(name,"UTF-8");
String encodedUrl =url1.replace(name,encode);
最后下载下来的文件名需要在filename的地方通过传的url去切割。