效果如图所示,
项目步骤以及源码如下
1 首先先写一个前端页面
index.jsp 源码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
名称:<input type="text" name="uname" ><br>
文件:<input type="file" name="myfile"><br>
<input type="submit" value="上传">
</form>
</body>
</html>
这里智能用post提交,如果用get提交的话请求的地址太长就不行,
2 然后写一个运行成功的页面success.jsp,作为跳转成功的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>success.jsp</h1>
<img src="uploadfile/${filename}">
</body>
</html>
3 这里这个上传文件的保存地址要先创建好,先建立一个有文件的文件夹,如果是空文件夹的话就有可能不编译而报错
4在web文件夹下还需要新建一个lib文件夹导包,导入后和以前一样的方法进入导包
5在src下创建上传的servlet
package com.yhp.web;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
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 javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
@WebServlet(value = "/upload")
public class UploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.创建对象
SmartUpload smartUpload = new SmartUpload();
//2.初始化
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 5, true);
smartUpload.initialize(pageContext);
//3.设置编码方式
smartUpload.setCharset("utf-8");
//4.上传
try {
smartUpload.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
}
//5.保存文件
File file = smartUpload.getFiles().getFile(0);
//6.得到文件的基本信息
String fileName = file.getFileName();
//指定服务器保存文件的路径
String url="uploadfile/"+fileName;
//保存文件
try {
file.saveAs(url,File.SAVEAS_VIRTUAL);
} catch (SmartUploadException e) {
e.printStackTrace();
}
//是否保存成功?--->如果上传成功,则页面中显示该文件
req.setAttribute("filename",fileName);
//7.测试:除文件以外的内容如何获取
String uname = smartUpload.getRequest().getParameter("uname");
System.out.println("uname="+uname);
//8.跳转页面
req.getRequestDispatcher("/success.jsp").forward(req,resp);
}
}
这样简单的文件上传就搞定了
所需要的包可以去网上下载