jquery-file-upload demo

下載地址:http://plugins.jquery.com/blueimp-file-upload/javascript

文檔地址:https://github.com/blueimp/jQuery-File-Upload/wikicss

本文只是一個demo,實現功能也很簡單:點擊一個上傳按鈕,用戶選擇圖片,圖片Ajax上傳到後臺存儲到硬盤,返回一個鏈接,頁面上顯示用戶上傳的圖片。html

(jquery-file-upload多文件上傳能夠作的很是漂亮,我這裏有點大材小用了)html5

注:demo 頁面爲jsp,服務端爲Java springMVC。java

頁面代碼:jquery

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">

<head>
    <meta charset="UTF-8">
    <title>file upload demo</title>
    
    <link rel="stylesheet" href="<c:url value ='/resource/themes/bootstrap/css/bootstrap.min.css'/>">
    <link rel="stylesheet" href="<c:url value ='/resource/js/jQuery-File-Upload/css/jquery.fileupload.css'/>">
     <script src="<c:url value ='/resource/js/jquery-1.9.1.min.js'/>"></script>
    <script src=" <c:url value ='/resource/js/jQuery-File-Upload/js/vendor/jquery.ui.widget.js'/>"></script>
    <script src=" <c:url value ='/resource/js/jQuery-File-Upload/js/jquery.iframe-transport.js'/>"></script>
    <script src=" <c:url value ='/resource/js/jQuery-File-Upload/js/jquery.fileupload.js'/>"></script>
    <script src="<c:url value ='/resource/themes/bootstrap/js/bootstrap.min.js'/>"></script>
    
     <script type="text/javascript">
    
     $(function () {
            var url = "/portal/upload/uploadImg.do";
            $('#fileupload').fileupload({
                url: url,
                dataType: 'text',
                done: function (e, data) {
                    console.dir(data);
                    $(".imgView img").attr('src','${contextPath}'+data.result);
                    $("#progress").hide();
                    $(".imgView").show();
                    
                },
                progressall: function (e, data) {
                    console.dir(data);
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#progress .progress-bar').css(
                        'width',
                        progress + '%'
                    );
                }
            });
        });
    </script>
</head>
<body>
    <span class="btn btn-success fileinput-button">
        <i class="glyphicon glyphicon-plus"></i>
        <span>Select file.</span>
        <!-- The file input field used as target for the file upload widget -->
        <input id="fileupload" type="file" name="imgFile"/>
    </span>
    <br>
    <br>
    <!-- The global progress bar -->
    <div id="progress" class="progress">
        <div class="progress-bar progress-bar-success"></div>
    </div>
    <div class="imgView" hidden="hidden">
        <img src="">
    </div>            
</body>
</html>

若是要本身寫cssgit

那麼只需如下四個js:jquery.min.jsjquery.ui.widget.jsjquery.iframe-transport.jsjquery.fileupload.jsgithub

配置:對id爲fileupload 的file input 進行fileupload實例化,url即爲圖片要上傳到服務端的後臺連接,也能夠經過html5的屬性 data-url 直接在input中給,input的name要給,或者經過配置 paramName屬性也是能夠的。progressall是配置進度條的,done是上傳到後臺返回後的事件。web

Java代碼:spring

 

import java.io.IOException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.isoftstone.veco.common.base.controller.BaseController;
import com.isoftstone.veco.common.upload.FileUploadHandler;

@RequestMapping("/upload")
@Controller
public class UploadController extends BaseController
{
    @RequestMapping("/uploadImg.do")
    public @ResponseBody
    String uploadMaterialImg(@RequestParam("imgFile") MultipartFile multipartFile)
    {
        String resp = null;
        if (multipartFile != null)
        {
            try
            {
                byte[] file = multipartFile.getBytes();
                String dir = "/test";
                String imgId = FileUploadHandler.uploadImg(file, dir);
                resp = FileUploadHandler.UPLOAD_CONFIG.getImgVirtualDir() + "?" + FileUploadHandler.UPLOAD_CONFIG.getDownloadParamName() + "="
                        + imgId;
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return resp;
    }

}

 

try中間的上傳邏輯就不詳細寫了,controller這裏寫的有點挫,應該返回一個json格式的,判斷上傳是否成功,給用戶反饋的,不過我這裏只是一個demo,哈哈

補充:增長對上傳圖片格式的驗證,以及對圖片大小的驗證,配置以下  
 $('#fileupload').fileupload({
                url: url,
                paramName:"imgFile",
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                maxFileSize: 5000000, // 5 MB
                dataType: 'text',
                done: function (e, data) {
                    console.dir(data);
                    $(".imgView img").attr('src','${contextPath}'+data.result);
                    $("#progress").hide();
                    $(".imgView").show();
                    
                },
                progressall: function (e, data) {
                    console.dir(data);
                    var progress = parseInt(data.loaded / data.total * 100, 10);
                    $('#progress .progress-bar').css(
                        'width',
                        progress + '%'
                    );
                },
                messages: {
                    acceptFileTypes: '圖片類型不合法 ',
                    maxFileSize: '圖片大小超過限制'
                }
            }).on('fileuploadprocessalways', function (e, data) {
                var index = data.index,
                file = data.files[index];
                if (file.error) {
                       alert(file.error);
                    }
          
                });
 

注: acceptFileTypes, maxFileSize這兩個屬性是jquery-file-upload中jquery.fileupload-validate.js中的,須要在進入兩個js文件:

jquery.fileupload-validate.js和jquery.fileupload-process.js

在經過註冊上傳後臺以前的事件fileuploadprocessalways 來獲取錯誤信息,若是不知道data中是什麼能夠經過 console.dir(data);在瀏覽器debug控制檯中查看

相關文章
相關標籤/搜索