首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Servet实现文件下传(fileupload)

2013-02-28 
Servet实现文件上传(fileupload)jsp使用servlet实现文件上传:1.首先要到apache官网上下载commons-fileuplo

Servet实现文件上传(fileupload)
jsp使用servlet实现文件上传:1.首先要到apache官网上下载commons-fileupload-1.2.2-bin.jar和其依赖的commons-io-2.4-bin.jar

Jsp:

<form action="UploadServlet" method="post" enctype="multipart/form-data">        username:<input type="text" name="username"><br>    file:<input type="file" name="file"><br>    file1:<input type="file" name="file1"><br>    <input type="submit" value="submit">            </form>

Servlet:

package com.wildcat.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UploadServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {DiskFileItemFactory factory=new DiskFileItemFactory();String path=request.getRealPath("/upload");factory.setRepository(new File(path));factory.setSizeThreshold(1024*1024);ServletFileUpload upload=new ServletFileUpload(factory);try{List <FileItem> list=(List <FileItem>)upload.parseRequest(request);for(FileItem item:list){String name=item.getFieldName();//调教的文本 域名if (item.isFormField()){//如果上传的是文本域String value=item.getString();//提交的内容System.out.println(name+" : "+value);request.setAttribute(name, value);}else {//如果上传的是文件String value=item.getName();//下面是对特殊浏览器的处理int start=value.lastIndexOf("\\");String fileName=value.substring(start+1);request.setAttribute(name, fileName);item.write(new File(path,fileName));}}}catch(Exception e){e.printStackTrace();}request.getRequestDispatcher("fileuploadResult.jsp").forward(request, response);}}


 


 

热点排行