25 Mayıs 2018 Cuma

Servlet Part Arayüzü

Giriş
Şu satırı dahil ederiz.
import javax.servlet.http.Part
multipart/form-data POST isteğindeki bir part'ı temsil eder.

Bu istek şuna benzer
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

getHeader metodu
Şöyle yaparız.
private String extractFileName(Part part) {

  String contentDisp = part.getHeader("content-disposition");
  String[] items = contentDisp.split(";");
  for (String s : items) {
    if (s.trim().startsWith("filename")) {
      return s.substring(s.indexOf("=") + 2, s.length() - 1);
    }
  }
  return "";
}
getInputStream metodu
Şöyle yaparız.
Part part = ...
InputStream stream = part.getInputStream();
Örnek
Şöyle yaparız.
InputStream input = part.getFile().getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer)) > 0;) 
  output.write(buffer, 0, length);

Hiç yorum yok:

Yorum Gönder