Servlet上傳圖片

如今一作東西就少不了,上傳這個,上傳那個的,那麼,個人構想是,servlet去上傳到服務器,也就是你指定的文件夾裏面,而後,在根據用戶最終肯定以後,在上傳到數據庫裏面。javascript

環境:web項目,包:commons-fileupload-1.2.1.jar,commons-io-1.4.jarcss

JAVA核心代碼  html

//這是上傳java

package com.upload.action;jquery

import java.io.File;
import java.io.IOException;
import java.util.List;web

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;ajax

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;數據庫

public class UploadServlet extends HttpServlet {apache

 private static final long serialVersionUID = 2121906815386996943L;服務器

 @SuppressWarnings("unchecked")
 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {

//初始化 FileItemFactory 
  FileItemFactory  factory = new DiskFileItemFactory();

// 初始化ServletFileUpload,能夠說是一個封裝好的的容器
  ServletFileUpload upload = new ServletFileUpload(factory);
  try {
   List<FileItem> list = upload.parseRequest(request);
   for (int i = 0; i < list.size(); i++) {
    FileItem fileItem = list.get(i);

//根據你想要的如XX.jpg等,來截取字符串
    String name = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\") + 1);

//保存,別說你不知道是什麼。。。。
    request.getSession().setAttribute(name, true);
    fileItem.write(new File("d:/upload/" + name));
    //這是上傳圖片的名字,若是隻規定上傳一次的話,那麼直接拿這個name,若是比較多的話,那麼。。。考慮中
    System.out.println(name);   
   }
   //方法1、直接放入集合中,而後循環讀出放入數據庫(放一個圖片就當即入庫)
   //方法2、再寫一個servlet,而後直接讀出upload下的子文件夾,放入數據庫(在確認這些圖片的狀況下,不進行改動的狀況下再去入庫)
   //考慮到可移植性的問題,那麼採起方法二
  } catch (FileUploadException e) {
   e.printStackTrace();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 

}

 

 

//這是刪除

 

package com.upload.action;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DeleteServlet extends HttpServlet {

 private static final long serialVersionUID = -4097655768318294837L;

 @Override
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  String fileName = request.getParameter("fileName");
  if(fileName != null) {
   boolean exist = false; 
   try{
    exist = (Boolean) request.getSession().getAttribute(fileName);
   }catch(Exception e) {
    return;
   }
   if(exist) {
    File file = new File("d:/upload/" + fileName);
    if(file.exists()) {
     file.delete();
    }
    request.getSession().removeAttribute(fileName);
   }
  }
 }

}

jsp頁面 能夠說是HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
    <style type="text/css">
     .deleteImg {
      cursor: pointer;
     }
     #uploaddiv img {
      margin-left: 20px;
     }
    </style>
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript" src="js/ajaxupload.3.5.js"></script>
    <script type="text/javascript">
     var uploadIndex = 1;
     $(function() {
       uploadIt();
       deleteFile();
     });
     function uploadIt() {

//最流行的jQuery,若是看不懂,那麼 sorry,這裏主要是上傳。
      $(".uploadAndNext").click(function() {
    var uploadId = "#" + $(this).attr("id");
       var btn = $(this);
       new AjaxUpload( uploadId + "" , {
          action : "UploadServlet" , 
         onChange: function(file, extension){
           $(uploadId + "").parent().find("input")[0].value = file;
           $(uploadId + "").parent().find(".uploadAndOkImg").show().attr("src" , "images/spinner.gif");
           btn.attr("disabled" , "disabled");
          },
          
          onComplete: function(file, response) {
       $(uploadId + "").parent().find(".uploadAndOkImg").attr("src" , "images/ok.gif");
       $(uploadId + "").parent().find(".deleteImg").attr("src" , "images/delete.gif").show();
       uploadIndex++;
       $("#uploaddiv").append("<div><input type='text' /><button class='uploadAndNext' id='upload" + uploadIndex + "'>瀏覽</button><img src='' width='20px' height='20px' class='uploadAndOkImg' style='display:none'/><img src='' width='20px' height='20px' class='deleteImg' style='display:none' alt='刪除'/></div>");
       uploadIt();
       deleteFile();
          }
       });
      });
     }
     function deleteFile() {
      $("#uploaddiv .deleteImg").click(function() {
        var fileName = $(this).parent().find("input").val();
        var thisObj = $(this);
        $.post("DeleteServlet" , {
         "fileName" : fileName
        },
         function(data) {
          thisObj.parent().remove();
         }
        );
       });
     }

//算了,仍是提示一下,是jQuery的Ajax,OK?
    </script>
  
  </head>
  
  <body>
    <div id="uploaddiv">
     <div><input type="text"  /><button  class="uploadAndNext" id="upload1">瀏覽</button><img src="" width="20px" height="20px" class="uploadAndOkImg" style="display: none"/><img src="" width="20px" height="20px" class="deleteImg" style="display:none;" alt="刪除"/></div>
    </div>
  </body>
  
</html>
注:有點很差使,可是學習完以後,你能夠本身創做。這只是個案例。

轉:http://liuyang-1989xy.blog.163.com/blog/static/1687545732010111061145523/

相關文章
相關標籤/搜索