【工具类】Java后台上传下载文件的几种方式
/** * 通过 HTTP PUT 请求将 JPG 照片上传至指定的腾讯云地址 * 协议要求: * <p> * PUT /<ObjectKey> HTTP/1.1 * Host: xxx.myqcloud.com //腾讯提供的Host地址 * Authorization: Auth String //每个图片的上传token,有效期为订单下发开始24h * [Object Content] //二进制照片内容 */ public void uploadImage(String localImagePath) throws Exception { // 1.将照片上传至腾讯地图众包侧提供的云服务上 try { File imageFile = new File(localImagePath); if (imageFile.exists()) { String url = "http://" + mapVendor.getHost() + mapVendorImageDetail.getBackUrl(); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "image/jpeg"); headers.add("Host", mapVendor.getHost()); headers.add("Authorization", mapVendorImageDetail.getBackAuth()); restTemplate.put(url, new HttpEntity<Resource>(new FileSystemResource(imageFile), headers)); } } catch (RestClientException e) { // 2.使用捕获异常来处理返回的非200的状态响应,如果非200则认定上传失败 logger.error("send local image [" + localImagePath + "] to tencent error", e); } }
/** * 以流的方式下载 * @param path 欲下载的文件的路径 * @param response 响应内容 * */ public void download(String path, HttpServletResponse response) { try { // path是指欲下载的文件的路径 File file = new File(path); // 取得文件名 String filename = file.getName(); // 取得文件的后缀名 String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase(); // 获取下载文件的输入流 InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); // 清空response response.reset(); // 重新设置response response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); // 写入下载文件的输出流 OutputStream outputStream = new BufferedOutputStream(response.getOutputStream()); outputStream.write(buffer); outputStream.flush(); outputStream.close(); } catch (IOException ex) { //TODO 记录日志并做相关业务 } }
/** * 把网络上的图片保存到本地 */ public void downloadNet() throws Exception { // 下载网络文件 int byteSum = 0; int byteRead; URL url = new URL("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png"); URLConnection conn = url.openConnection(); InputStream inputStream = conn.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream("c:/logo.gif"); // 存放读取的字节 byte[] buffer = new byte[1204]; while ((byteRead = inputStream.read(buffer)) != -1) { byteSum += byteRead; System.out.println(byteSum); fileOutputStream.write(buffer, 0, byteRead); } }
/** * 把网络上的图片保存到本地并支持在线打开 */ public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception { File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; response.reset(); // 非常重要 if (isOnLine) { // 在线打开方式 URL u = new URL("file:///" + filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); // 文件名应该编码成UTF-8 } else { // 纯下载方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); } OutputStream out = response.getOutputStream(); while ((len = br.read(buf)) > 0) out.write(buf, 0, len); br.close(); out.close(); }
青取之于蓝,再胜于蓝。
天不酬勤不够勤,勤到极处自酬人。 ---持续学习