Вам просто нужно сделать Http-FileUpload, который в особом случае POST.Нет необходимости кодировать файл.Нет необходимости использовать специальный lib / jar. Нет необходимости сохранять объект на диск (независимо от того, как это делает следующий пример)
Вы найдете очень хорошее объяснение команды Http-Command и как вашего особого фокуса "загрузить "под
с помощью java.net.URLConnection для запуска и обработки HTTP-запросов
Ниже приведен пример загрузки файла (смотрите" Отправить двоичный файл ") иМожно добавить некоторые сопутствующие данные либо
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF);
writer.append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).flush();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(textFile), charset));
for (String line; (line = reader.readLine()) != null;) {
writer.append(line).append(CRLF);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.flush();
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
InputStream input = null;
try {
input = new FileInputStream(binaryFile);
byte[] buffer = new byte[1024];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.
} finally {
if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}
writer.append(CRLF).flush(); // CRLF is important! It indicates end of binary boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF);
} finally {
if (writer != null) writer.close();
}
Относительно второй части вашего вопроса.При успешной загрузке файла (я использую общие файлы apache), нет ничего сложного в том, чтобы доставлять BLOB-объекты в виде изображений.
Это способ приема файла в сервлете
public void doPost(HttpServletRequest pRequest, HttpServletResponse pResponse)
throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
try {
FileItemIterator iter = upload.getItemIterator (pRequest);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String fieldName = item.getFieldName();
InputStream stream = item.openStream();
....
stream.close();
}
...
И этот код дает изображение
public void doGet (HttpServletRequest pRequest, HttpServletResponse pResponse) throws IOException {
try {
Blob img = (Blob) entity.getProperty(propImg);
pResponse.addHeader ("Content-Disposition", "attachment; filename=abc.png");
pResponse.addHeader ("Cache-Control", "max-age=120");
String enc = "image/png";
pResponse.setContentType (enc);
pResponse.setContentLength (img.getBytes().length);
OutputStream out = pResponse.getOutputStream ();
out.write (img.getBytes());
out.close();
Я надеюсь, что фрагменты этого кода помогут ответить на ваши вопросы