
上傳圖片.gif
html
<form id="fm_feedBack" enctype="multipart/form-data" method="post">
<div class="top-container">
<textarea name="content" id="adviceContent" name="" rows="" cols="" placeholder="把你使用過程的感受、意見告訴我們吧,我們會努力改進的!"></textarea>
</div>
<div class="photo-container">
//上傳圖片
<div class="pushPhoto" style="position: relative;">
<span class="close-btn" onclick="delImg(this)">X</span>
<img />
<input name="adviceImga" type="file" accept="image/*" value="+" capture="camera" onchange="imgPreview(this)">
</div>
<span class="photo-tips">上傳截圖</span>
</div>
<div class="line-container">
<input type="tel" name="phoneNo" id="contactMethod" value="" placeholder="請?zhí)顚懩穆?lián)系方式(手機/QQ都可以)"/>
</div>
<button type="button" class="btn" >提交反饋</button>
</form>
js
FileReader是html5定義的用于讀取文件的API,F(xiàn)ileReader接口有4個方法,其中3個用來讀取文件,另一個用來中斷讀取。無論讀取成功或失敗,方法并不會返回讀取結(jié)果,這一結(jié)果存儲在result屬性中。
- readAsBinaryString:將文件讀取為二進制編碼
- readAsText:將文件讀取為文本
- readAsDataURL:將文件讀取為DataURL
- abort : 終端讀取操作
FileReader接口的使用
if (window.FileReader) {
var reader = new FileReader();
} else {
alert("您的設備不支持圖片預覽功能,如需該功能請升級您的設備!");
}
//獲取文件
var file = fileDom.files[0];
//將文件以Data URL形式讀入頁面
reader.readAsDataURL(file);
reader.onload = function(e) {
//獲取結(jié)果
result = e.target.result;
}
確保用戶上傳的是圖片
var imageType = /^image\//;
//是否是圖片
if (!imageType.test(file.type)) {
alert("請選擇圖片!");
return;
}
css
不用input[type="file"]默認樣式所以將其透明度設為0,并為其父元素設置想要的樣式
input[type="file"]{
opacity: 0;
position:absolute;
width:100%;
height: 100%;
border:none
}
.pushPhoto>img{
position: absolute;
top: 0;
left: 0;
z-index: 1;
width:0%;
height: 0%;
}
.close-btn{
//刪除按鈕
display: none;
position: absolute;
right: 0;
top: 0;
color: #555;
font-size: 0.8rem;
background:#dcdcdc;
padding: 5% 8%;
z-index: 2;
}
.pushPhoto{
background: url(../img/advice_pic_btn.png) no-repeat center center;//樣式背景圖
background-size: contain;
}
表單上傳
serialize():輸出序列化表單值的結(jié)果
<form> 標簽的 enctype 屬性規(guī)定在發(fā)送到服務器之前應該如何對表單數(shù)據(jù)進行編碼
- application/x-www-form-urlencoded : 在發(fā)送前編碼所有字符(默認)
- multipart/form-data : 不對字符編碼。在使用包含文件上傳控件的表單時,必須使用該值。
- text/plain : 空格轉(zhuǎn)換為 "+" 加號,但不對特殊字符編碼。
$.ajax({
cache: true,
type: "POST",
url:URL,
data: $('#formId').serialize(),
async: false,
error: function(request) {
},
success: function(data) {
if(typeof(data)=="string"){
data=JSON.parse(data);
}
if(data.resultCode==1){
alertmsg(data.result);
}
}
});