By CaesarChang             

~关注我  带你看更多精品技术和面试必备

1.将jar包添加到项目中:smartupload.jar

2.准备上传的页面

<form action="toUpload" method="post" 
enctype="multipart/form-data"
>


书名
:<input type="text" name="bookName"/><br>


图片
:<input type="file" name="
自定义名称
"/><br>


<input type="submit" value="
提交
"/>


</form>



:(1)form
标签中要添加
enctype属性



(2)
提交方式必须是
post

3.开始获取数据,保存文件


实例代码:


@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();
//7制定服务器保存文件路径
String url="uploadFile/"+fileName;
//保存文件
try {
file.saveAs(url,File.SAVEAS_AUTO);
} catch (SmartUploadException e) {
e.printStackTrace();
}
// 是否保存成功
req.setAttribute("fileName",fileName);
System.out.println(fileName);
// 除文件以外的内容如何获取
String uname = smartUpload.getRequest().getParameter("uname");
System.out.println("+uname="+uname);
//跳转界面
req.getRequestDispatcher("/success.jsp").forward(req,resp);

}
}


smartupLoad实现文件上传(最全) 包会_git