事先准备jsmartcom_zh_CN.jar文件,用于文件上传准备,放到lib文件夹下

一、案例演示

选择图片1.png,点击上传,保存到根目录upload下
在这里插入图片描述

二、完成步骤

1.通过jsp内置java代码实现文件上传

1.1 文件上传代码

文件上传的html页面

//文件名upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <form action="do_upload.jsp" method="post" enctype="multipart/form-data">
        上传的图片:<input type="file" name="pic"><br>
                  <input type="submit" value="上传">
    </form>
</body>
</html>

1.2 处理上传代码

上传的文件进行保存

//文件名do_upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>处理上传</title>
</head>
<body>
<%
    SmartUpload smart=new SmartUpload();
    smart.initialize(pageContext);//初始化上传
    smart.upload();//上传准备
    smart.save("upload");//将文件保存到服务器根目录下,相应目录下
%>
</body>
</html>

1.3 服务器根目录创建upload文件

通过application.getRealPath()获取真实路径,在真实路径下建upload文件夹

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String url=application.getRealPath("/");
    System.out.println(url);
%>
</body>
</html>

2. 通过servlet实现处理上传

2.1 servlet代码

//创建UploadServlet
package servlet;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "UploadServlet", value = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        SmartUpload smart =new SmartUpload();
        smart.initialize(this.getServletConfig(),request,response);//初始化上传
        try {
            smart.upload(); //准备上传
            smart.save("upload");//保存文件夹
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}

2.2 配置xml(新版可不用配置)

<servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>servlet.UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/upload</url-pattern>
</servlet-mapping>

修改upload.jsp form表单action路径访问到servlet即可

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐