• jsp实现文件上传——douploadFile.jsp


    <%@page import="java.io.File"%>
    <%@page import="org.apache.commons.fileupload.FileItem"%>
    <%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
    <%@page import="org.apache.commons.fileupload.FileItemFactory"%>
    <%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%
    	request.setCharacterEncoding("utf-8");
    	//1.判断是不是文件上传表单
    	boolean ismultipart = ServletFileUpload.isMultipartContent(request);
    	if (ismultipart) {
    		//2.创建文件上传工厂
    		FileItemFactory fac = new DiskFileItemFactory();
    		//3.创建文件上传对象
    		ServletFileUpload fileUpload = new ServletFileUpload(fac);
    		//4.解析请求
    		List<FileItem> fileItemList = fileUpload.parseRequest(request);
    		//5.遍历集合,获取相应的数据
    		try {
    	for (FileItem item : fileItemList) {
    		//判断是普通表单数据还是文件数据
    		if (item.isFormField()) {
    			//true为普通表单
    			//获取提交过来表单name属性值
    			//文件上传中不能用下列方法取数据
    			//request.getParameter("userName");
    					String filedName = item.getFieldName();
    					if (filedName.equals("userName")) {
    						//封装用户信息
    						System.out.println("用户名"
    								+ item.getString("utf-8"));
    					} else if (filedName.equals("userPwd")) {
    						System.out.println("密码"
    								+ item.getString("utf-8"));
    					}
    				} else {
    					//false为文件表单
    					//6.获取文件名(全路径)
    					String fullFileName = item.getName();
    					//out.print(fullFileName);
    					File file1 = new File(fullFileName);
    					//只获取文件名,不包含路径
    					String fileName = file1.getName();
    					//7.根据虚拟路径来获取物理路径
    					String uploadPath = application
    							.getRealPath("upload/");
    					File file2 = new File(uploadPath, fileName);
    					item.write(file2);
    					out.print("上传成功!");
    				}//else
    			}//for
    		} catch (Exception ex) {
    			ex.printStackTrace();
    			out.print("上传失败");
    		}
    	}
    %>
    

  • 相关阅读:
    Hadoop学习之安装HDFS
    常见的6种数据结构
    maven 编译出错 Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean
    jquery解决js对象、数组赋值时的引用传递
    405 method not allowed(方法不被允许)
    身份证件号 正确性检查方法
    svn 提交信息模板
    idea 使用说明
    java-System类
    java-Integer 类
  • 原文地址:https://www.cnblogs.com/a1111/p/12816538.html
Copyright © 2020-2023  润新知