<form method="post" action="hi.iq/register.jsp" enctype="multipart/form-data">
Name: <input type="text" name="name">
file: <input type="file" name="file-upload">
<input type="submit">
</form>
Misal kita mau ambil 2 paramter (name & file-upload) tersebut. Pada file servlet, kita tidak bisa memakai kode seperti dibawah ini
request.getParameter("name");
Kalau kamu semua ambil seperti di bawah ini, maka hasilnya null. Dan supaya tidak null, maka cara panggilnya harus seperti ini
HashMap<String, String> hm = new HashMap<String, String>();
int maxMemorySize = 1024 * 1024 * 10;
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(maxMemorySize);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List<FileItem> uploadItems;
try {
InputStream is = null;
OutputStream os = null;
long sizeInBytes = 0L;
uploadItems = upload.parseRequest(request);
for (FileItem uploadItem : uploadItems) {
fieldName = uploadItem.getFieldName();
if (uploadItem.isFormField()) {
value = uploadItem.getString();
hm.put(fieldName, value);
} else {
value = uploadItem.getName();
contentType = uploadItem.getContentType();
boolean isInMemory = uploadItem.isInMemory();
sizeInBytes = uploadItem.getSize();
is = uploadItem.getInputStream();
System.out.println("contentType "+contentType+" isInMemory "+isInMemory);
}
System.out.println("fieldName "+fieldName+" value "+value);
}
/** upload app **/
name = hm.get("name");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("ERROR");
e.printStackTrace();
}
Kalau kurang jelas, bisa ke link ini
0 komentar:
Posting Komentar