JS上傳圖片實現代碼

來源:互聯網
上載者:User
本文主要和大家分享JS上傳圖片的實現代碼,本文主要以代碼的形式和大家分享,希望能協助到大家。

<!doctype html><html><head><meta name="baidu-site-verification" content="U4mw2VL8NF"/><meta charset="utf-8">   <title>上傳圖片</title><meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"><script src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js"></script><style>@media (min-width: 990px) {.container {width: 960px;}}</style></head><body>@include('header')<img id="pic" style="width:100px;height:100px;border-radius:50%;"src="/upload/thumbs/086fa7a88f4f4ab9fce23827a9fc6f22.jpg"><input id="upload" name="file" accept="image/*" type="file" style="display: none"/><!-- <ul>   <li style="width:23%;float:left;margin:10px;height:200px;background:#eee;">   <img style="height:200px;width:100%;" src="/upload/thumbs/efb3fb08b062a55e28a0e15ad2228514.jpg" alt=""></li></ul> --></body></html><script>$(function () {$("#pic").click(function () {$("#upload").click(); //隱藏了input:file樣式後,點擊頭像就可以本地上傳$("#upload").on("change", function () {var objUrl = getObjectURL(this.files[0]); //擷取圖片的路徑,該路徑不是圖片在本地的路徑if (objUrl) {$("#pic").attr("src", objUrl); //將圖片路徑存入src中,顯示出圖片upimg();}});});});//建立一個可存取到該file的urlfunction getObjectURL(file) {var url = null;if (window.createObjectURL != undefined) { // basicurl = window.createObjectURL(file);} else if (window.URL != undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file);} else if (window.webkitURL != undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file);}return url;}//上傳頭像到伺服器function upimg() {var pic = $('#upload')[0].files[0];//console.log(pic)var file = new FormData();file.append('image', pic);$.ajax({url: "/uploadImg",type: "post",data: file,cache: false,contentType: false,processData: false,success: function (data) {console.log(data);var res = data;//$("#resimg").append("<img src='/" + res + "'>")}});}// 需要注意幾點:// fd.append('name', file);// 這一句中的name是後台需要接受的file的name</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.