form上傳文件2種方式


示例1:

表單里有圖片/文件的上傳

<form enctype="multipart/form-data" method="post">

<input type="file" name="uploadfile"/>

</form>

multipart/form-data 是上傳二進制數據

form里面的input的值以2進制的方式傳過去,所以這里要明白,使用這種格式以后,后台request就獲取不到數據了

enctype屬性是設置提交數據的格式,指定將數據回發到服務器時瀏覽器使用的編碼類型。

 

enctype值:

application/x-www-form-urlencoded:窗體數據被編碼為名稱/值對。這是標准(默認)的編碼格式。

multipart/form-data:窗體數據被編碼為一條消息,頁上的每個控件對應消息中的一個部分。

text/plain:窗體數據以純文本形式進行編碼,其中不含任何控件或格式字符

 

示例2:jquery ajax無刷新上傳圖片

 

<form id='myupload' action='XXXXXXXXXXXX' method='post' enctype='multipart/form-data'>
<div class="demo">
<div class="btn">
    <span>添加附件</span>
    <input id="fileupload" type="file" name="file1">
</div>
<div class="progress">
    <span class="bar"></span><span class="percent">0%</span>
</div>
<!-- 顯示已上傳的文件名 -->
<div class="files"></div>
<!-- 顯示已上傳的圖片-->
<div class="showimg"></div>
</div>
<input type="submit" onclick="gosubmit2()"/>
</form>
<script type="text/javascript" src="jquery-form.js"></script>
<script type="text/javascript">
    var bar = $('.bar');//進度條
    var percent = $('.percent');//獲取上傳百分比
    var showimg = $('.showimg');//顯示圖片的div
    var progress = $('.progress');//顯示進度的div
    var files = $('.files');//文件上傳控件的input元素
    var btn = $('.btn span'); //按鈕文本
    function gosubmit2(){
        $("#myupload").ajaxSubmit({
            dataType :'json',//返回數據類型
            beforeSend:function(){
                showimg.empty();
                progress.show();
                var percentVal = '0%';
                bar.width(percentVal);
                percent.html(percentVal);
                btn.html('上傳中..');
            },
            //更新進度條事件處理代碼
            uploadProgress:function(event,position,total,percentComplete){
                var percentVal = percentComplete + '%';
                bar.width(percentVal);
                percent.html(percentVal);
            },
            success:function(data){//圖片上傳成功時
                //獲取服務器端返回的文件數據
                alert(data.name+","+data.pic+","+data.size);                
            },
            error:function(xhr){
                btn.html(上傳失敗);
                bar.width('0');
                files.html(xhr.responseText);
            }
        });
    }
</script>

 

jquery-form.js csdn下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM