java put 上传文件流
时间: 2024-06-09 11:07:18 浏览: 57
你可以使用Java的HttpURLConnection类来上传文件流。以下是一个示例代码:
```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) {
String fileUrl = "http://example.com/upload"; // 上传地址
String filePath = "/path/to/file"; // 文件路径
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("PUT");
conn.setDoOutput(true);
// 设置请求头
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("Content-Length", String.valueOf(new File(filePath).length()));
OutputStream out = conn.getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.flush();
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 上传成功
} else {
// 上传失败
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
这个例子中,我们使用PUT方法上传文件流,设置了Content-Type和Content-Length请求头,然后将文件流写入输出流中。最后,我们可以检查响应码来确定上传是否成功。
阅读全文