apache常用库文件上传
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文件中写入“导入”字样,其中提交按钮的值。怎么了。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里至少有一个问题:
如果您正在查看表单字段,为什么要查看它的InputStream?您应该只对非表单字段项目(即文件)感兴趣。
经过第二次检查,您正在使用 Commons IO,甚至不需要查看它的 InputStream。只要取消支票就可以了。
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.