zoukankan      html  css  js  c++  java
  • 不借助第三方jar包实现文件上传

            假设实现文件上传难道非要借助第三方jar包(最经常使用的莫过于apache的commons-fileupload工具包)来实现吗?答案是否定的。以下通过样例演示在不借助第三方jar包的前提下怎样实现文件的上传:

            1、servlet文件代码:

    package com.ghj.packageofservlet;
    
    import java.io.IOException;
    import java.util.UUID;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    
    import org.apache.commons.io.FilenameUtils;
    import org.apache.commons.lang.StringUtils;
    
    /**
     * 用于接收文件上传请求
     * 
     * @author GaoHuanjie
     */
    @WebServlet(urlPatterns = "/UploadServlet")
    @MultipartConfig(location = "C:/upload/", maxFileSize = 1024 * 1024 * 10)
    public class UploadServlet extends HttpServlet {
    	
    	private static final long serialVersionUID = 1L;
    
    	@Override
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doPost(request, response);
    	}
    	
    	@Override
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		request.setCharacterEncoding("UTF-8");
    	    try{
    	    	Part part = request.getPart("photo");
    	    	if(part.getSize() == 0l){
    	    		request.setAttribute("result", "请选择要上传的文件!!。");
    	    	}else{
    			    String fileSuffix = FilenameUtils.getExtension(StringUtils.substringBetween(part.getHeader("content-disposition"), "filename="", """));
    				part.write(UUID.randomUUID().toString() + "." + fileSuffix);
    				request.setAttribute("result", "文件成功上传。!!");
    	    	}
    	    }catch (Exception e) {
    			if(e.getMessage().contains("its maximum permitted  size ")){
    				e.printStackTrace();
    				request.setAttribute("result", "上传文件过大,请又一次选择!!

    !"); }else{ e.printStackTrace(); request.setAttribute("result", "系统出现故障,请联系管理员!。。"); } } request.getRequestDispatcher("result.jsp").forward(request, response); } }

            说明:上面servlet依赖于commons-io-2.4.jar和commons-lang-2.5.jar两个jar包。主要实现获取上传文件类型的功能。

            2、web.xml文件代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.0" 
    	xmlns="http://java.sun.com/xml/ns/javaee" 
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
        <welcome-file-list>
        	<welcome-file>index.jsp</welcome-file>
      	</welcome-file-list>
    </web-app>

            3、站点首页文件代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    <%
    	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title>借助Servlet3.0实现文件上传</title>
    	</head>
    	  
    	<body>
    		<form action="<%=basePath%>UploadServlet" method="post" enctype="multipart/form-data">
    			文件上传:<input type="file" id="photo" name="photo"/>
    			<input type="submit" value="開始上传" />
    		</form>
    	</body>
    </html>

            4、上传文件结果文件代码:

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title>文件上传结果</title>
    	</head>
    	  
    	<body>
    		<center style="margin-top: 20%">
    			<font style="font-size: 36pt;font-weight: bold;color: red;"><%=request.getAttribute("result") %></font>
    		</center>
    	</body>
    </html>
            【0分资源下载——servlet3.0文件上传 01.zip

            【0分资源下载——servlet3.0文件上传 02.zip

             说明:上面两个样例的代码基本同样,唯一的差别是:第一个样例是把文件上传到了C盘upload目录内,而第二个样例是把文件上传到了公布项目的server上。

  • 相关阅读:
    python反射
    numpy笔记
    leetcode43
    leetcode-42
    The Github Flow
    leetcode-37
    leetcode-41
    leetcode-40
    TCP扫盲2
    字节码分析与操作
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/5227124.html
Copyright © 2011-2022 走看看