java往服务器上传文件
时间: 2023-08-29 12:05:15 浏览: 41
要在Java中将文件上传到服务器,可以使用Java的HTTPURLConnection类或Apache的HTTPClient类。这里提供HTTPURLConnection类的示例代码:
```java
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";
String filePath = "/path/to/file.jpg";
String fileName = "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", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
OutputStream outputStream = conn.getOutputStream();
String header = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n" +
"Content-Type: image/jpeg\r\n" +
"\r\n";
outputStream.write(header.getBytes());
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
fileInputStream.close();
String footer = "\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n";
outputStream.write(footer.getBytes());
outputStream.flush();
outputStream.close();
System.out.println("File uploaded successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例代码中,我们将文件上传到了指定的服务器URL,使用了POST方法,指定了Content-Type为multipart/form-data,同时指定了文件的Content-Disposition和Content-Type。其中,boundary为自定义的分隔符,可以随意指定。在输出流中先写入header,再写入文件内容,最后写入footer。注意,这里的文件名需要与服务器端的处理代码中的参数名一致,才能正确接收并处理上传的文件。