您的位置:首页 > 编程语言 > Java开发

java实现文件上传

2010-03-25 14:55 302 查看
public class Upload extends HttpServlet {
private ServletContext sc;

private String savePath;

public Upload() {
super();
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator it = items.iterator();
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) {
System.out.println("表单的参数名称: " + item.getFieldName()
+ ",对应的参数值: " + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上传的文件的大小: " + item.getSize());
System.out.println("上传的文件的类型: " + item.getContentType());
System.out.println("上传的文件的名称: " + item.getName());
File tempFile = new File(item.getName());
System.out.println(tempFile.getName());
File file = new File(sc.getRealPath("/") + savePath,tempFile.getName());
System.out.println(file);
item.write(file);
request.setAttribute("upload.message", "文件上传成功");
} else {
request.setAttribute("upload.message", "没有选择上传文件");
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件不成功! ");
}
request.getRequestDispatcher("uploadResult.jsp").forward(request,response);
}

public void destroy() {
super.destroy();
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void init(ServletConfig config) throws ServletException {
savePath = "upload";
sc = config.getServletContext();

}
}

<form action="Up" method="post" enctype="multipart/form-data">
<table width="350" border="0" align="center">
<tr height="50">
<td colspan="2" align="center">文件上传</td>
</tr>
<tr align="center">
<td width="40%">上传文件</td>
<td><label>
<input type="file" name="uploadfile" id="uploadfile" />
</label></td>
</tr>
<tr align="center">
<td align="right"><label>
<input type="reset" name="button" id="button" value="重置" />
</label></td>
<td><label>
<input type="submit" name="button2" id="button2" value="提交" />
</label></td>
</tr>
</table>
</form>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: