1、导入jspSmartUpload.jar包。 2、在项目中创建上传文件夹upload,用来保存上传的文件的保存路径 我的项目的结构图如下:
3、编写上传界面。必须要设置ectype=“multipart/form-data”表示以二进制形式提交
<form action="UpAndDownServlet" enctype="multipart/form-data" method="post"> <input type="file" name="file"> <input type="submit" value="上传"> </form>4、编写相应的上传servlet代码 (1)、创建SmartUpload对象 (2)、初始化创建的SmartUpload对象 (3)、进行文件的上传 (4)、把上传的文件保存到服务器上相应的文件夹,我这里创建的是upload文件夹
@WebServlet("/UpAndDownServlet") public class UpAndDownServlet extends HttpServlet { private static final long serialVersionUID = 1L; //因为文件上传是通过form表单提交,method为post,所以上传操作要写在doPost方法中 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、创建SmartUpload对象 SmartUpload smartUpload = new SmartUpload(); //2、初始化创建的SmartUpload对象 smartUpload.initialize(getServletConfig(), request, response); try { //3、进行文件的上传 smartUpload.upload(); //4、把上传的文件保存到服务器上相应的文件夹,我这里创建的是upload文件夹 String fileSavePath = request.getServletContext().getRealPath("upload"); // 得到upload文件夹的路径 SmartFiles files = smartUpload.getFiles(); //得到所有上传的文件 for (int i = 0; i < files.getCount(); i++) { //遍历所有上传的每一个文件 SmartFile curFile = files.getFile(i); //得到当前上传的文件 //为了防止重名文件的bug,我们这里采用文件上传的时候作为文件名来保存 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS"); String filename = simpleDateFormat.format(new Date()); String fileExt = curFile.getFileExt(); //获得当前文件的后缀名 String lastFilePath = fileSavePath + "/" + filename + "." + curFile; //当前文件的存储路径 curFile.saveAs(lastFilePath); } } catch (SmartUploadException e) { e.printStackTrace(); } } }3、编写下载的jsp界面
<a href="UpAndDownServlet?down=1.png">1.png</a>4、编写文件下载对应的servlet代码
//因为下载视通过<a>标签链接的,所以采用的是doGet方法。 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1、创建SmartUpload对象 SmartUpload smartUpload = new SmartUpload(); //2、初始化创建的SmartUpload对象 smartUpload.initialize(getServletConfig(), req, resp); //3、文件下载(同时需要得到文件的下载路径。通过 下载的jsp页面的a连接的URL?后面的参数获得对应的文件名) String filename = req.getParameter("down"); //获得要下载的文件名 String fileSavePath = req.getServletContext().getRealPath("upload"); //因为文件是保存在服务器的upload文件夹中的,所以要获得文件夹的路径 String lastDownPath = fileSavePath + "/" + filename; //得到文件下载的最终路径 try { smartUpload.downloadFile(lastDownPath); //进行下载 } catch (SmartUploadException e) { e.printStackTrace(); } }