search
HomeWeb Front-endJS TutorialUploader transfers pictures to the server in seconds

This article mainly introduces the complete code of uploader to transfer pictures to the server in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

Let’s take a look at the renderings first:

##js part of the page


var f1 = null; 
var picarr = new Array(); 
var basearr = new Array(); 
var lat = "", 
  longt = ""; 
var files = []; 
// 上传文件 
function upload() { 
   
   
  var wt = plus.nativeUI.showWaiting(); 
  var task = plus.uploader.createUpload(server + "?action=dynamicadd", { 
      method: "POST" 
    }, 
    function(t, status) { //上传完成 
      if (status == 200) { 
//           console.log("上传成功:" + t.responseText); 
        mui.toast("发表成功"); 
        //插入本地数据库 
        wt.close(); 
        mui.back(); 
      } else { 
        console.log("上传失败:" + status); 
        wt.close(); 
      } 
    } 
  ); 
  var title = $("#tbxtitle").val(); 
  if (title.length < 1) { 
    wt.close(); 
    mui.toast("内容不能为空"); 
  } else {  
    task.addData("title", title); 
    task.addData("uid", getUid()); 
    task.addData("userid", plus.storage.getItem("policeid")); 
    //task.addData("lat", lat.toString()); 
    //task.addData("longt", longt.toString()); 
//       console.log("准备上传"+files.length+"个图片"); 
    for (var i = 0; i < files.length; i++) { 
      var f = files[i]; 
//         console.log("准备上传的图片路径:"+f.path); 
      task.addFile(f.path, { 
        key: f.name 
      }); 
    } 
    task.start(); 
  } 
   
} 
 
// 添加文件 
var index = 1; 
var newUrlAfterCompress; 
function appendFile(p) { 
  files.push({ 
    name: "uploadkey" + index,//这个值服务器会用到,作为file的key 
    path: p 
  }); 
  index++; 
} 
// 产生一个随机数 
function getUid() { 
  return Math.floor(Math.random() * 100000000 + 10000000).toString(); 
} 
 
function getposition() { 
  plus.geolocation.getCurrentPosition(function(p) { 
    var codns = p.coords; // 获取地理坐标信息; 
    lat = codns.latitude; //获取到当前位置的纬度; 
    longt = codns.longitude; //获取到当前位置的经度 
  }, function(e) { 
    //alert("获取百度定位位置信息失败:" + e.message); 
  }, { 
    provider: &#39;baidu&#39; 
  }); 
} 
 
function galleryImgs() { // 从相册中选择图片 
  plus.gallery.pick(function(e) { 
    $(".dynamic_images ul li").remove(".pickimg"); 
//       console.log("选择了"+e.files.length+"个图片"); 
    for (var i = 0; i < e.files.length; i++) { 
      if (i < 9) { 
        picarr[i] = e.files[i]; 
        $(".dynamic_images ul").prepend("<li class=&#39;pickimg&#39;><img  src="/static/imghwm/default1.png"  data-src="images/cbd.jpg"  class="lazy"  src=&#39;" + e.files[i] + "&#39; / alt="Uploader transfers pictures to the server in seconds" ></li>"); 
        var dstname="_downloads/"+getUid()+".jpg";//设置压缩后图片的路径 
        newUrlAfterCompress=compressImage(e.files[i],dstname); 
        appendFile(dstname); 
        //console.log(e.files[i]); 
        //console.log(dstname); 
      } 
    } 
  }, function(e) { 
    console.log("取消选择图片"); 
  }, { 
    filter: "image", 
    multiple: true 
  }); 
} 
 
//压缩图片,这个比较变态的方法,无法return 
function compressImage(src,dstname) { 
  //var dstname="_downloads/"+getUid()+".jpg"; 
  plus.zip.compressImage({ 
      src: src, 
      dst: dstname, 
      overwrite:true, 
      quality: 20 
    }, 
    function(event) { 
      //console.log("Compress success:"+event.target); 
      return event.target; 
    }, 
    function(error) { 
      console.log(error); 
      return src; 
      //alert("Compress error!"); 
    }); 
   
} 
//旋转图片,本文没用到 
function rotateImage() { 
  plus.zip.compressImage({ 
      src: "_www/a.jpg", 
      dst: "_doc/a.jpg", 
      rotate: 90 // 旋转90度 
    }, 
    function() { 
      alert("Compress success!"); 
    }, 
    function(error) { 
      alert("Compress error!"); 
    }); 
} 
 
function showActionSheet() { 
  var bts = [{ 
    title: "拍照" 
  }, { 
    title: "从相册选择" 
  }]; 
  plus.nativeUI.actionSheet({ 
      cancel: "取消", 
      buttons: bts 
    }, 
    function(e) { 
      if (e.index == 1) { 
        getImage(); 
      } else if (e.index == 2) { 
        galleryImgs(); 
      } 
    } 
  ); 
} 
//拍照 
function getImage() { 
  var cmr = plus.camera.getCamera(); 
  cmr.captureImage(function(p) { 
    plus.io.resolveLocalFileSystemURL(p, function(entry) { 
      var localurl = entry.toLocalURL(); // 
      $(".dynamic_images ul li").remove(".pickimg"); 
      $(".dynamic_images ul").prepend("<li class=&#39;pickimg&#39;><img  src="/static/imghwm/default1.png"  data-src="images/cbd.jpg"  class="lazy"  src=&#39;" + localurl + "&#39; / alt="Uploader transfers pictures to the server in seconds" ></li>"); 
    }); 
  }); 
}

Some operations for page initialization:


##

document.addEventListener("plusready", plusReady, false); 
 
function plusReady() { 
  document.getElementById("addnew").addEventListener("tap", function() { 
    showActionSheet();//拍照还是相册 
  }); 
  document.getElementById("fabiao").addEventListener("tap", function() { 
    upload();//上传文件 
  }); 
  plus.nativeUI.closeWaiting(); 
 
}

html layout, relatively simple, imitating WeChat:


<p class="dynamic_images"> 
  <ul> 
    <!--<li><img  src="/static/imghwm/default1.png"  data-src="images/cbd.jpg"  class="lazy"   alt="Uploader transfers pictures to the server in seconds" ></li>--> 
    <li><img  src="/static/imghwm/default1.png"  data-src="images/iconfont-tianjia.png"  class="lazy"   id="addnew" alt="Uploader transfers pictures to the server in seconds" ></li> 
    <!--<li><span class="mui-icon iconfont icon-jia2" style="font-size: 28px;"></span></li>--> 
 
  </ul> 
</p>

Server asp.net version


string file = ""; 
int count = Request.Files.Count; 
 
for (int i = 0; i < count; i++) 
{ 
  int l = Request.Files["uploadkey" + (i + 1)].ContentLength; 
  byte[] buffer = new byte[l]; 
  Stream s = Request.Files["uploadkey" + (i + 1)].InputStream; 
  System.Drawing.Bitmap image = new System.Drawing.Bitmap(s); 
  string imgname = Common.GetGuid() + ".jpg"; 
  string path = "Images/" + DateTime.Now.ToString("yyyyMMdd") + "/"; 
  if (!Directory.Exists(HttpContext.Current.Server.MapPath(path))) 
  { 
    System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path)); 
  } 
  image.Save(Server.MapPath(path + "/" + imgname)); 
}

The speed is very fast, tested , the speed will not drop significantly if it is not compressed, but considering the problem of loading during display, compression is still performed.

The CSS added later has no style:

<style type="text/css"> 
  .dynamic_images { 
    width: 100%; 
  } 
   
  .dynamic_images ul { 
    margin: 0; 
    padding: 0; 
  } 
   
  .dynamic_images ul li { 
    float: left; 
    list-style: none; 
    width: 25%; 
  } 
   
  .dynamic_images ul li img { 
    width: 98%; 
    height: 80px; 
  } 
</style>

The plus sign is the font: http://iconfont.cn/

Header The style is a secondary modification of the HB style. If you are not developing with HB, you can just write the CSS yourself.


Related recommendations:


Example explanation of H5 mobile development Ajax uploading multiple Base64 format pictures to the server

Example detailed explanation WeChat Mini program uploads pictures to the server

js implementation example of pasting and uploading pictures to the server and displaying them

The above is the detailed content of Uploader transfers pictures to the server in seconds. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor