欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JSP上傳文件到指定位置實例代碼

 更新時間:2013年10月17日 15:03:11   作者:  
復(fù)制上傳文件,上傳文件到服務(wù)器指定位置,注意,提交表單需要制定enctype的類型

Servlet 代碼:

復(fù)制代碼 代碼如下:

 /** 直接取上傳的File */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String targetPath = request.getRealPath(request.getContextPath()); // 目標(biāo)存儲路徑,服務(wù)器部署目錄下
  request.setCharacterEncoding("UTF-8");
  try {
   DefaultFileItemFactory factory = new DefaultFileItemFactory();
   DiskFileUpload up = new DiskFileUpload(factory);
   List<FileItem> ls = up.parseRequest(request);
   for (FileItem file : ls) {
    if (file.isFormField()) { // 判斷是文件還是文本信息
     System.out.println("表單參數(shù)名:" + file.getFieldName()+ ",表單參數(shù)值:" + file.getString("UTF-8"));
    } else {
     if (file.getName() != null && !file.getName().equals("")) { // 判斷是否選擇了文件
      File sFile = new File(file.getName());// 構(gòu)造臨時對象,此時文件暫存在服務(wù)器的內(nèi)存當(dāng)中
      File tFile = new File(targetPath, sFile.getName());
      if(tFile.exists()){
       System.out.println("同名文件已上傳!");
      }else{
        //FileUtils.copyFileToDirectory(sFile, tFile);//直接復(fù)制并上傳到服務(wù)器,自動生成上機目錄,目錄名稱與上傳文件的名稱一致
       FileUtils.copyFile(sFile, tFile); // 直接復(fù)制并上傳文件到服務(wù)器,直接在指定位置生成目標(biāo)文件
       System.out.println("文件上傳成功");
       if (tFile.isDirectory()) { // 刪除上傳文件
        FileUtils.deleteDirectory(tFile);
       } else if (tFile.isFile()) {
        tFile.delete();
       }
       System.out.println("文件刪除成功");
      }
     } else {
      System.out.println("沒有選擇上傳文件!");
     }
    }
   }
  } catch (FileUploadException e) {
   System.out.println("文件上傳失?。?);
   e.printStackTrace();
  }
 }

Servlet配置:web.xml

復(fù)制代碼 代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>test.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/servlet/MyServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

Html頁面:

復(fù)制代碼 代碼如下:

<body>
   <form method="post" action="servlet/MyServlet" encType="multipart/form-data" >
    <font color="blue">可直接發(fā)布zip文件</font> <br />
          發(fā)布流程文件 :<input type="file" name="processDef" />
   <input type="submit"  value="部署"/>
 </form>
  </body>

相關(guān)文章

最新評論