smartUpload原生开发非常实用的文件上传工具

smartupload的简介

​ smartupload是www.jspsmart.com这个网站发布的一套上传下载的组件包,可以轻松的完成文件的上传、下载等操作。

smartupload实现上传

​ 使用smartupload实现上传的基本步骤:

  • 实用化SmartUpload对象

  • 初始化上传文件

  • 准备上传

  • 保存文件

范例:

<!-- 用于文件上传的表单 -->

​	<form  action=${pageContext.request.contextPath}/servlet/SmartuploadDemo01"

​	 method="post" enctype="multipart/form-data">

​		选择文件:<input type="file" name="file"><!-- 文件选择框 --><br>

​		文件描述:<input type="text" name="fileDec"><br><button>提交</button></form>

这是上传文件的前端代码,接下来新建一个Servlet

@WebServlet("/servlet/SmartuploadDemo01")

public class SmartuploadDemo01 extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//		- 实用化SmartUpload对象

​		SmartUpload smartUpload = new SmartUpload();//		- 初始化上传文件(需要使用pageContxt对象)

//		①获取pageContext对象

​		JspFactory jspFactory = JspFactory.**getDefaultFactory**();

​		PageContext pageContext = jspFactory.getPageContext(this, request, response, null, false, 0, false);

//		②初始化上传文件

​		smartUpload.initialize(pageContext);try {

//		- 准备上传

​			smartUpload.upload();

//		- 保存文件

​			smartUpload.save("file");//保存到指定的根目录的file中

​			Request res = smartUpload.getRequest();//必须使用smartUpload提供的request对象,否则参数不能正常接收

​			String fileDec = res.getParameter("fileDec");byte b[] = fileDec.getBytes();

​			fileDec = new String(b,"utf-8");

​			System.out.println("-------------"+fileDec+"------------");} catch (SmartUploadException e) {

​			e.printStackTrace();}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throw ServletException, IOException {doGet(request, response);}

}

这样,我们就完成了上传文件的操作了。

小结

smartUpload在原生开发中非常实用,使用时需先导入jar包,jar包可以去官网下载

​ 选择文件的框一定需要name属性,否则上传不能够成功

​ 必须使用smartUpload提供的request对象,否则参数(即上面fileDec的内容)不能正常接收

猜你喜欢

转载自blog.csdn.net/codeliang20/article/details/106580379