jsp实现文件上传
文章目录一、案例演示二、文件上传2.处理上传总结提示:以下是本篇文章正文内容,下面案例可供参考一、案例演示选择图片1.png,点击上传,保存到根目录upload下二、文件上传代码如下(示例):写出文件上传的基本模块<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head&g
·
文章目录
事先准备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即可
更多推荐
已为社区贡献6条内容
所有评论(0)