如何把文件上傳到文件服務(wù)器 java

在Java中,上傳文件到文件服務(wù)器通??梢酝ㄟ^多種方式實(shí)現(xiàn),例如使用`HttpURLConnection`進(jìn)行HTTP POST請求,或者使用第三方庫如Apache H...
在Java中,上傳文件到文件服務(wù)器通??梢酝ㄟ^多種方式實(shí)現(xiàn),例如使用`HttpURLConnection`進(jìn)行HTTP POST請求,或者使用第三方庫如Apache HttpClient、OkHttp等。以下是一個使用`HttpURLConnection`上傳文件的簡單示例:
```java
import java.io.;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void uploadFile(String targetUrl, File file) throws IOException {
URL url = new URL(targetUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type", "multipart/form-data");
httpConn.setRequestProperty("Content-Length", String.valueOf(file.length()));
httpConn.setRequestProperty("Content-Disposition", "form-data; name="file"; filename="" + file.getName() + """);
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestMethod("POST");
try (OutputStream out = httpConn.getOutputStream()) {
Files.copy(file.toPath(), out);
本文鏈接:http:///bian/361523.html
上一篇:請教12英寸是多少厘米?