java往服务器写入文件的代码
时间: 2024-04-28 19:22:05 浏览: 14
要在Java中向服务器写入文件,可以使用Java的HTTPURLConnection类或Apache的HTTPClient类。这里提供HTTPURLConnection类的示例代码:
```java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) {
String serverUrl = "http://example.com/upload";
String filePath = "/path/to/file.jpg";
try {
File file = new File(filePath);
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/octet-stream");
conn.setRequestProperty("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
FileInputStream fileInputStream = new FileInputStream(file);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
dos.write(buffer, 0, bytesRead);
}
dos.flush();
fileInputStream.close();
dos.close();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
System.out.println("File uploaded successfully!");
} else {
System.out.println("File upload failed with response code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码中,我们将文件上传到了指定的服务器URL,使用了POST方法,指定了Content-Type为application/octet-stream,同时指定了文件的Content-Disposition为attachment,表示附件,文件名为原文件名。在输出流中写入文件内容,最后关闭输出流。注意,这里的文件名需要与服务器端的处理代码中的参数名一致,才能正确接收并处理上传的文件。其中,如果服务器返回的状态码为200表示上传成功,否则上传失败。