java input 上传文件至服务器
时间: 2023-09-05 22:13:26 浏览: 102
好的,对于java input上传文件至服务器,您可以使用以下代码:
```java
import java.io.*;
import java.net.*;
public class FileUploader {
public static void main(String[] args) {
String fileUrl = "http://localhost:8080/upload"; // 上传接口地址
String filePath = "C:\\test\\test.txt"; // 被上传的文件路径
try {
URL url = new URL(fileUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
File file = new File(filePath);
OutputStream outputStream = conn.getOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream));
// 开始上传文件
dataOutputStream.writeBytes("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n");
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n");
dataOutputStream.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) != -1) {
dataOutputStream.write(buffer, 0, length);
}
dataOutputStream.writeBytes("\r\n");
dataOutputStream.writeBytes("------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n");
fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();
// 获取响应码,如果成功返回200
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
// 上传成功
System.out.println("上传成功!");
} else {
// 上传失败
System.out.println("上传失败!");
}
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
希望能对您有所帮助!
阅读全文