import java.net.HttpURLConnection;
import java.net.URL;
import java.io.*;
public static String uploadFile(String targetUrl,MultipartFile file,String knowledgeBaseName) throws IOException {
String boundary = Long.toHexString(System.currentTimeMillis());
String CRLF = "\r\n";
URL url = new URL(targetUrl);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.setRequestMethod("POST");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Java Multipart Upload Client");
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = httpConn.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
) {
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"files\"; filename=\"" + file.getOriginalFilename() + "\"").append(CRLF);
writer.append("Content-Type: " + file.getContentType()).append(CRLF);
writer.append(CRLF).flush();
InputStream fileInputStream = file.getInputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
output.flush();
fileInputStream.close();
writer.append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"knowledge_base_name\"").append(CRLF);
writer.append(CRLF).append(knowledgeBaseName).append(CRLF).flush();
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"override\"").append(CRLF);
writer.append(CRLF).append(String.valueOf(true)).append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
}
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
return response.toString();
} else {
return httpConn.getResponseMessage();
}
}

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73