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) {
}
}
}
html表单:
<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>
当我在其中保存时创建index.jpg但在jpg文件中写入“import”字,其中提交按钮的值。怎么了。感谢。
答案 0 :(得分:0)
这里至少有一个问题:
if(item.isFormField()){
InputStream uploadedStream = item.getInputStream();
...
}
如果您正在查看表单字段,为什么要查看其InputStream?您应该只对非表单字段项目感兴趣,即文件。
第二次检查时,您正在使用Commons IO,甚至不需要查看其InputStream。只是否定支票,你会没事的。