帮我写一个java上传文件接口
时间: 2023-03-09 12:24:28 浏览: 67
我可以为您提供一个简单的Java上传文件接口的示例:import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;public class UploadFile { public static void main(String[] args) {
String urlString = "http://example.com/upload";
String filePath = "/path/to/file.txt";
String charset = "UTF-8";
File uploadFile = new File(filePath);
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
String twoHyphens = "--"; try {
URLConnection connection = new URL(urlString).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary); try (
OutputStream output = connection.getOutputStream();
InputStream input = new FileInputStream(uploadFile)
) {
output.write((twoHyphens + boundary + CRLF).getBytes(charset));
output.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadFile.getName() + "\"" + CRLF).getBytes(charset));
output.write(("Content-Type: text/plain" + CRLF).getBytes(charset));
output.write(CRLF.getBytes()); byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.write(CRLF.getBytes());
output.write((twoHyphens + boundary + twoHyphens + CRLF).getBytes());
} // Process the response
int responseCode = connection.getResponseCode();
System.out.println(responseCode); } catch (IOException e) {
e.printStackTrace();
}
}
}