package com.liaoxuefeng.web;
public class FileUploadServlet extends HttpServlet {
private String uploadDir = "C:\\temp";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// TODO:
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
try {
ServletFileUpload upload = new ServletFileUpload();
// set max file size to 1 MB:
upload.setFileSizeMax(1024 * 1024);
FileItemIterator it = upload.getItemIterator(req);
// handle with each file:
while (it.hasNext()) {
FileItemStream item = it.next();
if (! item.isFormField()) {
// it is a file upload:
handleFileItem(item);
}
}
req.getRequestDispatcher("success.jsp").forward(req, resp);
}
catch(FileUploadException e) {
throw new ServletException("Cannot upload file.", e);
}
}
void handleFileItem(FileItemStream item) throws IOException {
System.out.println("upload file: " + item.getName());
File newUploadFile = new File(uploadDir + "/" + UUID.randomUUID().toString());
byte[] buffer = new byte[4096];
InputStream input = null;
OutputStream output = null;
try {
input = item.openStream();
output = new BufferedOutputStream(new FileOutputStream(newUploadFile));
for (;;) {
int n = input.read(buffer);
if (n==(-1))
break;
output.write(buffer, 0, n);
}
}
finally {
if (input!=null) {
try {
input.close();
}
catch (IOException e) {}
}
if (output!=null) {
try {
output.close();
}
catch (IOException e) {}
}
}
}
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.uploaddir = config.getInitParameter("dir");
}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>com.liaoxuefeng.web.FileUploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/upload</url-pattern> </servlet-mapping> </web-app>
<html> <body> <p>FileUploadServlet Demo</p> <form name="form1" action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" name="button" value="Submit" /> </form> </body> </html>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有