1. 程式人生 > >Servlet3.0 多圖片,檔案上傳

Servlet3.0 多圖片,檔案上傳

1.分析

上傳檔案的過程:客服端選擇一個檔案後,寫入到伺服器端,伺服器端使用一個目錄來儲存該檔案--底層IO流操作

2.jsp檔案上的表單設計

表單傳輸格式用multipart/form-data,要上傳的檔案input標籤name屬性最好用同樣的字首或者字尾好獲取

<form method="post" class="form-x" action="${pageContext.request.contextPath}/UserServlet.action?method=updateImg"   enctype="multipart/form-data" >  
              <
div class="form-group"> <div class="label"> <label>圖片:</label> </div> <div class="field"> <input type="text" class="input tips" style="width:25%; float:left;" data-toggle="hover" data-place
="right" data-image="${pageContext.request.contextPath}/images/headimg.jpg" /> <input type="file" class="button bg-blue margin-left" name="myfile1" style="float:left;"> <div class="tipss">圖片尺寸:500*500</div> </div> </
div> <div class="field"> <button class="button bg-main icon-check-square-o" type="submit"> 提交</button> </div> </form>

3後臺Servlet處理

1.Servlet 上增加註解@MultipartConfig一定要寫 )不寫嘿嘿你可以試試讓你瘋狂卻找不到錯誤程式碼

@MultipartConfig
public class UserServlet extends HttpServlet {

content-disposition頭欄位不懂點連結:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Content-Disposition

高版本瀏覽器現在F12看不到這個資訊了

public void updateImg(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //傳虛擬路徑返回真實路徑
        String path = this.getServletContext().getRealPath("/images");
        //要解析檔案域 要用getPart方法 getPart方法得到的是一個檔案域 
        //使用getParts()獲取表單使用multipart/form-data傳輸格式發過來的請求體,其中包含了檔案域引數
        //返回的是Part物件的集合,每個Part就是表單中的一個引數,可以是普通表單元素(如文字框),也可以是特殊的File(檔案域)
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            //獲取請求體中的引數名字
            String name = part.getName();             //解析表單引數,如果名稱是myfile1,說明part是一個File 當然是別的就可以用字串比較即可比如以file開頭的: part.getName().startsWith("file")         if("myfile1".equals(name)){
//說明當前part是一個檔案域,獲取content-disposition頭欄位的值
                //格式:form-data;name="myfile1";filename="adv_1.jpg"
                String header = part.getHeader("Content-Disposition");
                String oldName = this.getOldName(header);
                //獲取新的檔名
                String newName = this.newName(oldName);
                //把檔案儲存在伺服器的images目錄下
                part.write(path+"/"+newName);
                
                //將影象更新到資料庫中 
                
            }
        }
        
    }
    
    //從content-disposition中獲取檔名
    public String getOldName(String header){
        //分割整個字串,得到陣列[form-data,name="myfile1",filename="adv_1.jpg"]
        String[] array = header.split(";");
        String filenameStr = array[2];        
        filenameStr = filenameStr.substring(filenameStr.indexOf("\"")+1, filenameStr.length()-1);
        return filenameStr;
    }
    //根據原始檔名生成新的檔名
    public String newName(String oldName){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String format = sdf.format(new Date());
        format += oldName;
        return format;
    }

 注意:這是上傳到tomcat伺服器上的直接在myEclipse工作空間中是找不到的,然後把路徑存到資料庫中就可以通過瀏覽器訪問該圖片了