在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 }