用Java写一个上传文件的功能函数
时间: 2023-02-26 18:04:29 浏览: 115
好的,以下是使用 Java 上传文件的示例代码:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Map;
public class FileUploader {
private static final String LINE_FEED = "\r\n";
/**
* 使用 POST 方法上传文件
*
* @param requestURL 请求的 URL
* @param fileFormName 文件表单字段的名称
* @param file 文件对象
* @param authHeader 认证的头信息(可选)
* @param otherParams 其他参数(可选)
* @return 服务器的响应信息
* @throws Exception
*/
public static String uploadFile(String requestURL, String fileFormName, File file,
String authHeader, Map<String, String> otherParams) throws Exception {
HttpURLConnection connection = null;
OutputStream outputStream = null;
BufferedReader reader = null;
try {
// 创建连接
URL url = new URL(requestURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + getBoundary());
// 设置认证的头信息
if (authHeader != null && !authHeader.isEmpty()) {
connection.setRequestProperty("Authorization", authHeader);
}
// 获取输出流
outputStream = connection.getOutputStream();
// 写入文件数据
outputStream.write(("--" + getBoundary() + LINE_FEED).getBytes());
outputStream.write(("Content-Disposition: form-data; name=\"" + fileFormName + "\"; filename=\""
+ file.getName() + "\"" + LINE_FEED).getBytes());
outputStream.write(("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName()) + LINE_FEED)
.getBytes());
outputStream.write(("Content-Transfer-Encoding: binary" + LINE_FEED).getBytes());
outputStream.write(LINE_FEED.getBytes());
FileInputStream inputStream =
阅读全文