java怎么上传下载图片
时间: 2023-03-31 17:00:56 浏览: 99
Java上传下载文件并实现加密解密
Java 可以使用 HttpURLConnection 或者 HttpClient 来进行图片的上传和下载。具体实现可以参考以下代码:
上传图片:
```
URL url = new URL(uploadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("--" + boundary + "\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n");
dos.writeBytes("Content-Type: image/jpeg\r\n\r\n");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int count = ;
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, , count);
}
fis.close();
dos.writeBytes("\r\n--" + boundary + "--\r\n");
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
is.close();
```
下载图片:
```
URL url = new URL(imageUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
int count = ;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, , count);
}
is.close();
byte[] data = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(savePath);
fos.write(data);
fos.close();
```
阅读全文