Java WebApp Asynchronous upload picture implementation code _java

Source: Internet
Author: User
Tags foreach wrapper

How to implement the Java WebApp Asynchronous upload picture, first understand the following questions:

1. Picture upload;
2. Picture upload preview;
3. Upload picture change address asynchronously add to database;

Main content
This sample mainly uses the pure HTML front-end and the JavaScript code as the tool, inquires about the demo its realization picture uploads The code example as follows:
(1) Click the div code to upload the picture:

<div id= "Div1" class= "photo" > 
 <input type= "file" id= "choose" accept= "image/*" multiple >
 <a id= "Upload" > Upload pictures </a> 
 <a class= "myinputimg" onclick= "Selectphoto ();" > Choose </a>
 <a class= "myinputimg" id= "Back" > Cancel </a> </div> from the gallery

(2) JavaScript code

<script type= "Text/javascript" >//Get upload image of input table cell element var filechooser = document.getElementById ("choose");
 Create a canvas var canvas = document.createelement ("canvas") for compressing a picture;
 Gets the visual attributes of canvas var ctx = Canvas.getcontext (' 2d ');
 Tile canva var Tcanvas = document.createelement ("Canvas");
 var tctx = Tcanvas.getcontext ("2d");
 Size of the canvas var maxsize = 100 * 1024;
  Upload Picture Click event $ ("#upload"). On ("click", Function () {Filechooser.click ();
  }. On ("Touchstart", function () {///add element attribute $ (this). addclass ("touching");
  }. On ("Touchend", function () {//remove element attribute $ (this). Removeclass ("touching");
 });
 Element change Filechooser.onchange = function () {//If the selection is NULL, returns the operation if (!this.files.length) return;
 Create an array of uploaded images var files = Array.prototype.slice.call (this.files); Select for the number of more than 1, back operation, here according to the requirements set; PC-side test can upload several pictures at a time, the mobile side to choose one, the page can only preview a picture.
 Because it is the moving end, so make this judgment.
  if (Files.length >1) {alert ("Upload only 1 pictures at a time");
 Return
 //traversal of the uploaded image file array, can not be traversed, direct access. Files.foreach (function (file, i) {//Judge picture format if (!/\/: jpeg|png|gIF)/i.test (File.type)) return;
  var reader = new FileReader ();
var li = document.createelement ("Li"); Get picture size var size = file.size/1024 > 1024?
  (~ ~ (file.size/1024/1024))/ten + "MB": ~ ~ (file.size/1024) + "KB"; Picture preview li.innerhtml = ' <div class= ' progress ' ><span></span></div><div class= ' size ' > ' +
  Size + ' </div> ';
  Append picture preview code; $ (". Img-list"). Append ($ (LI));
  Reader.onload = function () {var result = This.result;
  var img = new Image ();
  IMG.SRC = result;
  The picture shows $ (li). css ("background-image", "url (" + result +) ");
   If the picture size is less than 100kb, direct upload if (result.length <= maxsize) {img = null;
   Upload (result, File.type, $ (LI));
  Return
  //image compression after loading, and then upload if (img.complete) {callback ();
  else {img.onload = callback;
   function callback () {var data = compress (IMG);
   Upload (data, File.type, $ (LI));
  img = NULL;
  }
  };
 Reader.readasdataurl (file);
 });
 }; The following is picture compression related;//using CanvasLarge picture compression function compress (img) {var initsize = img.src.length;
 var width = img.width;
 var height = img.height;
 If the picture is greater than 4 million pixels, compute the compression ratio and press the size below 4 million VAR ratio;
  if ((ratio = width * height/4000000) > 1) {ratio = math.sqrt (ratio);
  Width/= ratio;
 Height/= ratio;
 else {ratio = 1;
 } canvas.width = width;
 Canvas.height = height;
 Lay the ground color Ctx.fillstyle = "#fff";
 Ctx.fillrect (0, 0, canvas.width, canvas.height);
 If the picture pixel is greater than 1 million, use tile to draw var count; if ((count = width * height/1000000) > 1) {count = ~ ~ (math.sqrt (count) + 1);/calculate how many tiles to divide/calculate the width and height of each tile and the Var NW
  = ~ ~ (width/count);
  var NH = ~ ~ (height/count);
  Tcanvas.width = NW;
  Tcanvas.height = NH; for (var i = 0; i < count; i++) {for (var j = 0; J < Count; j) {Tctx.drawimage (img, I * NW * ratio, J * NH
   * ratio, NW * ratio, NH * ratio, 0, 0, NW, NH);
  Ctx.drawimage (Tcanvas, I * NW, J * NH, NW, NH);
 }} else {Ctx.drawimage (img, 0, 0, width, height); //Minimum compression var ndata = canVas.todataurl (' Image/jpeg ', 0.1);
 Console.log (' before compression: ' + initsize);
 Console.log (' compressed after: ' + ndata.length);
 Console.log (' Compression rate: ' + ~ ~ (initsize-ndata.length)/initsize) + "%");
 Tcanvas.width = Tcanvas.height = Canvas.width = Canvas.height = 0;
 return ndata; //Picture upload, turn base64 picture into binary object, Cram Formdata upload function upload (basestr, type, $li) {var text = Window.atob (Basestr.split (",")
 [1]);
 var buffer = new Uint8array (text.length);
 var pecent = 0, loop = null;
 for (var i = 0; i < text.length i++) {Buffer[i] = text.charcodeat (i);
 The var blob = GetBlob ([buffer], type);
 var xhr = new XMLHttpRequest ();
 var formdata = Getformdata ();
 Formdata.append (' upload ', blob); Asynchronous request Kindeditor plugin upload picture jsp page Xhr.open (' Post ', ' <%=request.getcontextpath ()%>/kindeditor/jsp/upload_
 Json.jsp '); Xhr.onreadystatechange = function () {if (xhr.readystate = = 4 && xhr.status = 200) {//Return server-side picture address Var fa
  Ce_img=xhr.responsetext;
  var id=$ ("#arId"). Text (); To add a picture $.aja the asynchronous image databaseX ({type: POST,//asynchronous request Struts's action class inserts the picture address into the database URL: "Add_article_faceurl.action", DataType: "JSON", Data: "FA Ceurl= "+face_img+" &id= "+id, Async:true, Success:function (msg) {//To add the ID value associated with the picture in the database, in the page hidden area $ (" #arId "). T
   EXT (msg);   
  }, Error:function (a) {}});
 }
 };
  Simulate upload progress Show//Data send progress, top 50% shows the progress Xhr.upload.addEventListener (' Progress ', function (e) {if (loop) return;
  Pecent = ~ ~ (+ * e.loaded/e.total)/2;
  $li. Find (". Progress span"). CSS (' width ', pecent + "%");
  if (pecent = =) {mockprogress ();
 }}, False);
  The data after 50% uses the simulated progress function mockprogress () {if (loop) return;
  loop = SetInterval (function () {pecent++;
  $li. Find (". Progress span"). CSS (' width ', pecent + "%");
  if (pecent = =) {clearinterval (loop);
 }, 100);
 } xhr.send (Formdata);
  /** * Get the compatibility of BLOB objects * @param buffer * @param format * @returns {*}/function GetBlob (buffer, format) {try {
 return new Blob (buffer, {type:format}); catch (e) {VAR bb = new (window. Blobbuilder | | Window. Webkitblobbuilder | | Window.
  Msblobbuilder);
  Buffer.foreach (function (buf) {bb.append (BUF);
  });
 return Bb.getblob (format); /** * Get Formdata/function Getformdata () {var isneedshim = ~navigator.useragent.indexof (' Android ') &&am P ~navigator.vendor.indexof (' Google ') &&!~navigator.useragent.indexof (' Chrome ') &&
 Navigator.userAgent.match (/applewebkit\/(\d+)/). Pop () <= 534; Return Isneedshim?
 New Formdatashim (): New FormData (); /** * Formdata Patch for Android that does not support Formdata upload blob * @constructor/function Formdatashim () {Console.warn (' using
 Formdata Shim '); var o = this, parts = [], boundary = Array. Join ('-') + (+new Date () * (1E16 * math.random ()). ToString, OldS
 end = XMLHttpRequest.prototype.send; This.append = function (name, value, filename) {Parts.push ('--' + boundary + ' \r\ncontent-disposition:form-data; Name= ')
  ' + name + ' "'); if (value instanceof Blob) {partS.push ('; filename= ') ' + (filename | |
  ' blob ') + ' "\r\ncontent-type: ' + value.type + ' \r\n\r\n ');
  Parts.push (value);
  else {parts.push (' \r\n\r\n ' + value);
 } parts.push (' \ r \ n ');
 };
  Override XHR Send () XMLHttpRequest.prototype.send = function (val) {var fr, data, oxhr = this;
  if (val = = O) {//Append the final boundary string Parts.push ('--' + boundary + '--\r\n ');
  Create the BLOB data = GetBlob (parts);
  The Set up and read "blob" into a array to is sent FR = new FileReader ();
  Fr.onload = function () {Oldsend.call (OXHR, Fr.result);
  };
  Fr.onerror = function (err) {throw err;
  };
  Fr.readasarraybuffer (data); Set the multipart content type and boudary this.setrequestheader (' Content-type ', ' multipart/form-data; boundary= ' + b
  Oundary);
  XMLHttpRequest.prototype.send = Oldsend;
  else {Oldsend.call (this, Val);
 }
 }; } </script>

(3) kindeditor plugin upload picture JSP page related code.

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ page import=" java.util.*,java.io.* "%> <%@ page import=" Java.text.SimpleDateFormat "%> <%@ page import=" org.apache.commons.fileupload.* "%> <%@ page import=" org.apache.commons.fileupload.disk.* "%> <%@ page import=" org.apache.commons.fileupload.servlet.* "%> <% @ Page import= "org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper"%> <%@ page import= "
 org.json.simple.* "%> <%/** * Kindeditor JSP * * This JSP program is a demo program, it is recommended not to use directly in the actual project.
 * If you are sure to use this program directly, please carefully confirm the relevant security settings before use.
* *//File Save directory path String Savepath = Pagecontext.getservletcontext (). Getrealpath ("/") + "attached/";
String Savepath = "http:\\\\192.168.1.226:8080\\qslnbase\\uploadfile/";
String Savepath = "d:/www/qslnadp/adp/webroot/kindeditor/attached/";
File save Directory URL String saveurl = Request.getcontextpath () + "/attached/"; Defines the file extensions allowed to be uploaded hashmap<string, string> extmap = new HashmAp<string, string> ();
Extmap.put ("image", "Gif,jpg,jpeg,png,bmp,blob");
Extmap.put ("Flash", "swf,flv");
Extmap.put ("Media", "SWF,FLV,MP3,WAV,WMA,WMV,MID,AVI,MPG,ASF,RM,RMVB");

Extmap.put ("File", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");

Maximum file size long maxSize = 1000000; Response.setcontenttype ("text/html;

Charset=utf-8 "); if (! Servletfileupload.ismultipartcontent (Request) {out.println (geterror) (please select a file.)
 "));
Return
//Check directory File uploaddir = new file (Savepath); if (!uploaddir.isdirectory ()) {out.println (GetError) ("Upload directory does not exist.")
 "));
Return //Check Directory Write permission if (!uploaddir.canwrite ()) {out.println (GetError) ("Upload directory does not have write permission.")
 "));
Return
String dirname = Request.getparameter ("dir"); if (dirname = = null) {dirname = "image";} if (!extmap.containskey (dirname)) {out.println (GetError ("Incorrect directory name.")
 "));
Return
//Create folder Savepath + = DirName + "/";
Saveurl + = dirname + "/";
File Savedirfile = new file (Savepath);
if (!savedirfile.exists ()) {savedirfile.mkdirs ();} SimpleDateFormat SDF = new SimpleDateFormat ("YyyyMMdd");
String ymd = Sdf.format (New Date ());
Savepath + = Ymd + "/";
Saveurl + = Ymd + "/";
File Dirfile = new file (Savepath); if (!dirfile.exists ()) {dirfile.mkdirs ();}//struts2 request wrapper filter Multipartrequestwrapper wrapper = (Multipartrequestwrappe

R) Request;

Get uploaded filename String fileName1 = wrapper.getfilenames ("upload") [0];

Get file filter filename = wrapper.getfiles ("upload") [0]; Check the file size if (File.length () > MaxSize) {out.println (GetError) ("The Upload file size exceeds the limit.")
 "));
Return
//Check extension String fileExt1 = filename1.substring (Filename1.lastindexof (".") + 1). toLowerCase ();
Refactoring upload filename SimpleDateFormat df1 = new SimpleDateFormat ("Yyyymmddhhmmss");

String newFileName1 = Df1.format (New Date ()) + "_" + New Random (). Nextint (1000) + "." + FileExt1;
byte[] buffer = new byte[1024];
Gets the file output stream FileOutputStream fos = new FileOutputStream (Savepath + newFileName1);
String Url=savepath + newFileName1;
Out.println (URL);

Gets the current file input stream in memory inputstream in = new FileInputStream (file); try {int Num = 0;
 while (num = in.read (buffer) > 0) {fos.write (buffer, 0, num);
 } catch (Exception e) {e.printstacktrace (system.err);} finally {in.close ();
Fos.close ();
}%> <%!
 private string GetError (String message) {Jsonobject obj = new Jsonobject ();
 Obj.put ("Error", 1);
 Obj.put ("message", message);
return obj.tojsonstring ();
 }%>

(4) The jar package for the Kindeditor upload image is as shown below
A.commons-fileupload-1.2.1.jar
B.commons-io-1.4.jar
C.json_simple-1.1.jar

Here is no use for Kindeditor JS code, specific reference: Kindeditor to realize the automatic image upload function

(5) About kindeditor upload a picture preview of the div below

<div id= "Div2" >
 <ul class= "img-list" >
  <li id= "WY" >
   /shequ/images/index.png; ">
  </li>
 </ul> 
</div>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.