Java是一種跨平臺、面向?qū)ο蟮木幊陶Z言,具有廣泛的應(yīng)用范圍。其中,照片上傳和下載是Java應(yīng)用中的常見需求。本文將介紹Java如何完成照片上傳和下載的功能。
照片上傳
/** * 上傳照片 * @param file 照片文件 * @param url 上傳接口地址 * @return 上傳成功后返回的結(jié)果 */ public static String uploadPhoto(File file, String url) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); FileBody fileBody = new FileBody(file); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addPart("file", fileBody); HttpEntity entity = builder.build(); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); return EntityUtils.toString(responseEntity, "utf-8"); } return null; }
照片下載
/** * 下載照片 * @param url 照片地址 * @param destFile 存儲路徑 * @return 下載成功后返回的結(jié)果 */ public static String downloadPhoto(String url, File destFile) { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); try { CloseableHttpResponse response = httpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); OutputStream out = new FileOutputStream(destFile); entity.writeTo(out); out.close(); return "下載成功!"; } } catch (IOException e) { e.printStackTrace(); } return null; }
通過以上代碼,可以很方便地實現(xiàn)Java應(yīng)用中的照片上傳和下載功能。