本文最后更新于 2026-06-07,文章内容可能已经过时。

1.引入包

实现文件上传需要使用到SmartUpload组件,需要引入对应jar包:

SmartUpload.jar

2.代码实现

前端

  • 通过jQuery的Ajax向servlet上传文件;
  • formData也可以直接用form创建,如:var formData = new FormData($( "#formId" )[0]);
<body>

	<input id="file" type="file" >
	<input id="upload" type="button" value="上传">

</body>
<script type="text/javascript">
	$(function() {
		$("#upload").click(function() {

			var formData = new FormData();
			formData.append('file', $("#file")[0].files[0]);
			alert(formData);
			$.ajax({
				url : '${pageContext.request.contextPath}/TankImportServlet',
				type : 'post',
				data : formData,
				dataType : 'json',
				async : true,
				cache : false,
				processData : false,
				contentType : false,
				success : function(data) {
					alert(data.result );
				},
				error : function() {
					alert("错误");
				}

			});

		});

	});
</script>

后端

  • servlet层
public class TankImportServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String filePath = "";//文件路径
		String filename="";//文件名
		//创建Smart Upload文件上传对象
		SmartUpload su=new SmartUpload();
		//初始化对象,规定写法,无需理解
		su.initialize(this.getServletConfig(), request, response);
		
			
					try {
						su.upload();//上传准备
						filename=su.getFiles().getFile(0).getFileName();
						filePath="e:\\"+filename;
						//保存到指定路径
						su.getFiles().getFile(0).saveAs(filePath);
					} catch (SmartUploadException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				

		json.put("result", true);
		out.print(json);

	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}
}