1. 程式人生 > >JSP—表單資訊與圖片同時上傳

JSP—表單資訊與圖片同時上傳

// Check that we have a file upload request 檢查是否是表單檔案上請求  
boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
// Create a new file upload handler 建立上傳物件  
ServletFileUpload upload = new ServletFileUpload();  
  
// Parse the request  
FileItemIterator iter = upload.getItemIterator(request); //得到所有的上傳資料  
while (iter.hasNext()) { //迴圈上傳表單的元素  
    FileItemStream item = iter.next();  
    String name = item.getFieldName(); //得到元素名  
    InputStream stream = item.openStream();  
    if (item.isFormField()) { //如果是普通元素,列印元素名與值  
        System.out.println("Form field " + name + " with value "  
            + Streams.asString(stream) + " detected.");  
    } else {//如果是檔案型的元素,列印元素名與檔名  
        System.out.println("File field " + name + " with file name "  
            + item.getName() + " detected.");  
        // Process the input stream  
        ...//儲存檔案  
    }  
}