图片上传到文件服务器的Java代码
时间: 2024-05-17 07:14:54 浏览: 150
好的,以下是一个简单的Java代码示例,用于将图片上传到文件服务器。假设您使用的是HTTP协议进行文件上传,文件服务器的上传接口地址为`http://example.com/upload`,要上传的图片文件路径为`/path/to/image.jpg`。
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) {
String serverUrl = "http://example.com/upload";
String fileToUpload = "/path/to/image.jpg";
try {
uploadFile(serverUrl, fileToUpload);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void uploadFile(String serverUrl, String fileToUpload) throws IOException {
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---BOUNDARY");
OutputStream outputStream = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
writer.println("---BOUNDARY");
writer.println("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileToUpload + "\"");
writer.println("Content-Type: image/jpeg");
writer.println();
writer.flush();
FileInputStream inputStream = new FileInputStream(fileToUpload);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.println();
writer.println("---BOUNDARY--");
writer.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 文件上传成功,获取服务器返回的响应内容
InputStream responseStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream));
String responseLine;
while ((responseLine = reader.readLine()) != null) {
System.out.println(responseLine);
}
reader.close();
} else {
// 文件上传失败,获取服务器返回的错误信息
InputStream errorStream = connection.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
String errorLine;
while ((errorLine = reader.readLine()) != null) {
System.err.println(errorLine);
}
reader.close();
}
connection.disconnect();
}
}
```
以上代码仅供参考,具体的实现方式和细节会根据使用的文件服务器和上传接口的不同而有所不同。您需要根据实际情况进行调整和修改。
阅读全文