java上传图片stringBuffer
时间: 2023-11-19 11:05:48 浏览: 92
JAVA通过HttpURLConnection 上传和下载文件的方法
您可以使用以下代码将图片转换为字符串并上传:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageUploader {
public static void main(String[] args) throws Exception {
String imageUrl = "http://example.com/image.jpg"; // 图片的URL地址
String boundary = "---------------------------" + System.currentTimeMillis(); // 分隔符
URL url = new URL("http://example.com/upload"); // 上传接口的URL地址
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
// 添加图片数据
writer.append("--").append(boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n");
writer.append("Content-Type: image/jpeg\r\n\r\n");
writer.flush();
InputStream in = new URL(imageUrl).openStream();
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
out.flush();
in.close();
writer.append("\r\n").flush();
// 添加其他参数
writer.append("--").append(boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"param1\"\r\n\r\n");
writer.append("value1").append("\r\n");
writer.flush();
writer.append("--").append(boundary).append("--\r\n");
writer.close();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
reader.close();
System.out.println(stringBuffer.toString());
}
}
```
阅读全文