zoukankan      html  css  js  c++  java
  • 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);
    		
    	}
    
    }
    


     


     

  • 相关阅读:
    Python3.4 + Django1.7.7 搭建简单的表单并提交
    python3.4 + Django1.7.7 表单的一些问题
    TypeScript(10): String(同JS)
    TypeScript(09): Number(同JS)
    TypeScript(08): 循环
    TypeScript(07): 条件语句(同JS)
    TypeScript(06): 运算符(同JS)
    TypeScript(05): 变量声明
    TypeScript(04): 基础类型
    TypeScript(03):基础语法
  • 原文地址:https://www.cnblogs.com/lixingle/p/3313000.html
Copyright © 2011-2022 走看看