public void execute(HttpServletRequest request) throws Exception {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1*1024*1024*1024); //1 MB
/*
* Set the temporary directory to store the uploaded files of size above threshold.
*/
factory.setRepository(new File("c:\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
InputStream uploadedStream = item.getInputStream();
try {
File f = new File("C:\\temp\\index.jpg");
item.write(f);
uploadedStream.close();
}
catch (IOException e) {
}
}
}
the html form:
<form enctype="multipart/form-data" method="POST" action="<%=request.getContextPath ()%>/main?cmd=ci">
<table class = "lineable">
<tr>
<td><input type="file" name="file1"/></td>
<td><input type="submit" name="q" value="import"/></td>
</tr>
</table>
</form>
When i save in it create index.jpg but writes “import” word in the jpg file which value of submit button. What is wrong. thanks.
At least one problem here:
If you’re looking at a form field, why should you look at its InputStream? You should only be interested in non form field items, ie files.
Upon second inspection, you’re using the Commons IO, and you don’t even need to look at its InputStream. Just negate the check and you’ll be fine.