图片上传到服务器java代码
时间: 2023-12-01 16:02:54 浏览: 31
以下是一个简单的 Java 代码示例,用于将图片上传到服务器:
```java
import java.io.*;
import java.net.*;
public class ImageUploader {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/upload"); // 替换为实际的上传地址
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
String boundary = "---------------------------" + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = conn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true);
// 添加图片数据
File file = new File("image.jpg"); // 替换为实际的图片文件路径
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"").append("\r\n");
writer.append("Content-Type: image/jpeg").append("\r\n\r\n");
writer.flush();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.flush();
fileInputStream.close();
writer.append("\r\n").flush();
// 添加其他表单数据
writer.append("--" + boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"title\"").append("\r\n");
writer.append("\r\n");
writer.append("Title").append("\r\n");
writer.flush();
writer.append("--" + boundary + "--").append("\r\n");
writer.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 上传成功
} else {
// 上传失败
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先创建了一个 `HttpURLConnection` 对象,并将其请求方法设置为 `POST`。然后我们设置了请求头中的 `Content-Type` 为 `multipart/form-data`,并指定了一个随机的边界字符串。接下来,我们将图片数据和其他表单数据写入到请求体中,并通过 `out.write()` 方法将数据发送到服务器。最后,我们检查服务器响应的状态码,以确定上传是否成功。请注意,此示例仅适用于上传单个图片文件,如果您需要上传多个文件,则需要进行相应的修改。