使用JAVA写一个文件上传代码
时间: 2023-03-26 15:02:35 浏览: 95
你好,以下是使用 Java 编写文件上传代码的示例:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FileUploader {
public static void main(String[] args) throws IOException {
String url = "http://example.com/upload";
String filePath = "/path/to/file.txt";
File file = new File(filePath);
String boundary = "---------------------------" + System.currentTimeMillis();
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("User-Agent", "Java File Uploader");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
String fileName = file.getName();
String contentType = "application/octet-stream";
String fieldName = "file";
String boundaryPrefix = "--";
String lineEnd = "\r\n";
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix).append(boundary).append(lineEnd);
sb.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(lineEnd);
sb.append("Content-Type: " + contentType).append(lineEnd);
sb.append(lineEnd);
byte[] headerBytes = sb.toString().getBytes("UTF-8");
byte[] footerBytes = (lineEnd + boundaryPrefix + boundary + boundaryPrefix + lineEnd).getBytes("UTF-8");
long contentLength = file.length() + headerBytes.length + footerBytes.length;
connection.setRequestProperty("Content-Length", Long.toString(contentLength));
connection.connect();
InputStream inputStream = null;
try {
inputStream = connection.getInputStream();
} catch (IOException e) {
inputStream = connection.getErrorStream();
}
byte[] buffer = new byte[4096];
int bytesRead = -1;
sb.setLength();
while ((bytesRead = inputStream.read(buffer)) != -1) {
sb.append(new String(buffer, , bytesRead, "UTF-8"));
}
System.out.println(sb.toString());
}
}
请注意,这只是一个示例代码,您需要根据实际情况进行修改和调整。
阅读全文