jsp+servlet实现文件上传

jsp页面代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css"> 
-->
</head>
<body>
	<form action="<%=path %>/upload" method="post"
		enctype="multipart/form-data">
		请选择上传的图片或文件:<input type="file" name="fileName" /><input type="submit"
			value="上传" />
	</form>
</body>
</html>

servlet代码

package com.hwua.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

/**
 * Servlet implementation class UpLoadServlet
 */
@WebServlet("/upload")
public class UpLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String realPath;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		realPath = getServletContext().getRealPath("/");
		System.out.println(realPath);
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		  // 创建上传文件项的工厂类
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8"); 
        DiskFileItemFactory fac = new DiskFileItemFactory();
        // 文件上传核心类对象
        ServletFileUpload upload = new ServletFileUpload(fac);
 
        try {
            // 把请求数据封装为 List<FileItem>
        	 List<FileItem> list = (List<FileItem>)upload.parseRequest(new ServletRequestContext(req));
            // 遍历,所有的上传文件项
            for (FileItem item : list) {
 
                // 上传文件项
                    String name = item.getName();
                    
                    System.out.println(name);
                    String[] split = name.split("\\\\");//Java 截取反斜杠 replaceAll和split (“\”) 问题解决办法 
                    String fileName=split[split.length-1];
                    //String value = item.getString();    // 上传文件内容
                    String type = item.getContentType(); // 文件类型
                    InputStream in = item.getInputStream(); // 上传文件文件流
                     
                    // 上传到upload目录
                    String basePath = getServletContext().getRealPath("/");
                    // 上传文件
                    FileOutputStream out = new FileOutputStream(new File(basePath,fileName));
                    byte[] b = new byte[1024];
                    int len = -1;
                    while ((len = in.read(b))!= -1) {
                        out.write(b, 0, len);
                    }
                    // 关闭
                    out.close();
                    in.close();
                
 
            }
 
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
 
		

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值