采用jspSmartUpload组件进行文件的上传
在web应用技术中经常使用文件的上传于下载,以下我效果以下我的代码了:
1.首先先导入 jsmartcom_zh_CN.jar 包
2.jsp页面的代码:
1 <%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'index.jsp' starting page</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 选择上传: 25 <form action="Upservlet" method="post" enctype="multipart/form-data"> 26 选择1:<input type="file" name="up1"><br/> 27 选择2:<input type="file" name="up2"> 28 <input type="submit" name="submit" value="提交"> 29 </form> 30 </body> 31 </html>
3.Upservlet对应下的Java代码:
1 package com.zuxia.servlet; 2 3 import java.io.IOException; 4 import javax.servlet.ServletException; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import com.jspsmart.upload.File; 9 import com.jspsmart.upload.Files; 10 import com.jspsmart.upload.SmartUpload; 11 public class Upservlet extends HttpServlet { 12 13 14 public void doGet(HttpServletRequest request, HttpServletResponse response) 15 throws ServletException, IOException { 16 17 doPost(request, response); 18 } 19 20 21 public void doPost(HttpServletRequest request, HttpServletResponse response) 22 throws ServletException, IOException { 23 24 //设置编码格式 25 request.setCharacterEncoding("GB2312"); 26 response.setCharacterEncoding("GB2312"); 27 28 //第一步:新建一个对象 29 SmartUpload smart=new SmartUpload(); 30 31 //第二步:初始化 32 smart.initialize(super.getServletConfig(), request, response); 33 34 //第三步:设置上传文件的类型 35 smart.setAllowedFilesList("jpg,html,pdf,txt,zip"); 36 37 try { 38 //第三步:上传文件 39 smart.upload(); 40 41 //第四步:保存文件 42 //smart.save("/imges"); 43 //对文件进行重命名 44 Files fs= smart.getFiles();//得到所有的文件 45 46 for (int i = 0; i <fs.getCount(); i++) {//对文件个数进行循环 47 48 File f=fs.getFile(i); 49 50 if (f.isMissing()==false) {//判断文件是否存在 51 52 f.saveAs("/imges/"+System.currentTimeMillis()+f.getFileName()); 53 } 54 55 } 56 57 58 } catch (Exception e) { 59 60 e.printStackTrace(); 61 } 62 63 } 64 65 }