java将图片文件上传到指定服务器目录
时间: 2023-06-13 21:06:30 浏览: 179
Java如何实现上传文件到服务器指定目录
5星 · 资源好评率100%
你可以使用Java中的URLConnection类来实现文件上传。下面是一个简单的示例代码:
```
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) {
String serverUrl = "http://example.com/upload.php"; // 服务器上传接口地址
String filePath = "path/to/image.jpg"; // 本地文件路径
String serverPath = "/var/www/html/uploads/"; // 服务器目标路径
try {
// 创建连接
URL url = new URL(serverUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=---------------------------123821742118716");
connection.setRequestProperty("Content-Disposition", "form-data; name=\"file\"; filename=\"" + new File(filePath).getName() + "\"");
// 读取文件并写入请求体
FileInputStream fileInputStream = new FileInputStream(new File(filePath));
OutputStream outputStream = connection.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
// 结束请求体
outputStream.flush();
outputStream.write("\r\n".getBytes());
outputStream.write("-----------------------------123821742118716--\r\n".getBytes());
// 发送请求并获取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
System.out.println("文件上传成功!");
} else {
System.out.println("文件上传失败,错误代码:" + responseCode);
}
// 关闭连接
fileInputStream.close();
outputStream.close();
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们创建一个HTTP连接对象,并设置请求头部信息。然后,我们读取本地文件,将其写入请求体,再发送请求并获取响应。最后,我们关闭连接。请注意,这段代码只是一个示例,你需要根据自己的实际情况进行修改。
阅读全文