Tml5+canvas+jquery realize the mobile phone photo upload picture Instance source code

Source: Internet
Author: User
Tags base64 file upload mkdir

Because for a while, I've been working on a micro-credit project, which involves the function of the document upload, the beginning of a little clue is not, the Internet to check a lot of information, QQ group inside also asked a lot of people, many people say that if it is app program, you can apply for system permissions, and then to call the system at the bottom of things, But the micro-mail is operating in the browser, our custom page is also through the micro-mail built-in browser open, and micro-trust browser in a lot of special processing, shielding a lot of things, so it is impossible to invoke the camera on the page or open the Library directory of the mobile system, of course, These are only theoretical speculation, and after I looked at the data for two days, I found that the problem can be resolved, and the implementation of the process is incredibly simple. Just use the HTML5 file upload function, and then with canvas can. The source code is attached below:


<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:14PX;" ><! DOCTYPE html>
<meta name= "viewport" content= "Height=device-height, Width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, User-scalable=no ">
<meta name= "format-detection" content= "Telephone=yes" >
<meta charset= "UTF-8" >
<title> Upload ID </title>
<style>
Body {
margin:20px 20%;
Color: #777;
Text-align:center;
}
#result {
margin-top:20px;
}
</style>
<body>
<input type= "File"/>
<div id= "Result" ></div>

<!--introduction of jquery-->
<script type= "Text/javascript" src= ". /js/jquery/jquery-1.9.1.min.js "></script>
<script type= "Text/javascript" src= ". /js/localresizeimg.js "></script>

<!--mobilebugfix.js compatible repair mobile device-->
<script src= ". /js/mobilebugfix.mini.js "type=" Text/javascript "></script>
<script type= "Text/javascript" >
$ ("Input:file"). Localresizeimg ({
WIDTH:500,
quality:0.8,
Success:function (Result) {
var img = new Image ();
IMG.SRC = result.base64;
Console.log (RESULT.CLEARBASE64);
$ ("Body"). Append (IMG);
$ ("#result"). empty ();
$ ("#result"). Append (IMG); Render image (photo shoot)
$.ajax ({
URL: "Uploadimageservlet",
Type: "POST",
DATA:{FORMFILE:RESULT.CLEARBASE64},
DataType: "HTML",
timeout:1000,
Error:function () {
Alert ("Error loading PHP document");
},
Success:function (Result) {
alert (result);
Console.log (result);
Alert ("Uploads success~")
}
});
}
});
</script>
</body>


The implementation of the above process led to this, first in the front of the image compression, because the phone is different, there may be some mobile phone camera to the force, pixel high, the picture taken out of the size of a relatively large number, so here through a plug-in compression, and then converted into Base64 code, Then the BASE64 code using AJAX to post to the server, and then in the Java or PHP background Base64 decoding, the solution is the path to upload the image path address, and then stored, written to the file or database inside.


In addition, here is a question to illustrate: many people are talking about the micro-mail built-in browser, I have always thought that the micro-trust built-in browser is the micro-trust the development of a browser, and then a lot of things are limited. In fact, the micro-letter itself did not re-create a browser, but the system itself called the browser, according to the different systems of the mobile phone changes. The micro-letter built-in browser calls the mobile phone system default browser, iOS and Android system default browser is the WebKit kernel, but the HTML5 and CSS3 support level may be different. Because browsers are only part of the system, the default browser for the system will not be upgraded individually, and the level of support for HTM5 and CSS3 is very much related to the system version. Android Micro-letter calls the system browser kernel directly, iOS is called Safari, you can see the following 1 and 3 effect is the same, 1 is the micro-letter browser Open, 3 is the Phantom of the MX 3 with the System browser open effect.

I have tested the above, can run normally. Attached below are a few photos:


1, this is the effect of opening in the micro-letter



2, this is in the mobile phone UC Browser Open effect:



3, this is in the system with the browser to open the effect (PS: My phone is the Phantom of the Family MX 3), but this is not open the System library directory, but directly to the system's folder root directory.



1, the front desk JS code:

$.ajax ({
async:false,//is asynchronous
cache:false,//whether to use caching
Type: "POST",
Data:{filedata:filedata,licencename:licencename,cust_tax_code:cust_tax_code,phonenum:phonenum,state_id:state_ ID},
DataType: "JSON",
timeout:1000,
ContentType: ' application/x-www-form-urlencoded; Charset=utf-8 ',
URL: $ (' #ctx '). Val () + "Customercheckservlet?action=uploadlicence",
Success:function (Result) {
Console.log (result);
if (result = = True) {
Alert (' Success upload~~~ ');
}else if (result = = False) {
Alert (' Error upload~~~ ');
}
},
Error:function () {
Alert ("Error linking~");
}
});

2, background Java code

/**
* Document Upload
* @param request
* @param response
* @throws IOException
*/
public void Uploadlicence (HttpServletRequest request,httpservletresponse response) throws ioexception{
Log.info ("=====================uploadlicence");
DF = new SimpleDateFormat ("Yyyy-mm-dd");

String Cust_tax_code = Request.getparameter ("Cust_tax_code");
String phonenum = Request.getparameter ("Phonenum");
String licencename = Request.getparameter ("Licencename");

String filedata = Request.getparameter ("Filedata"),//BASE64 encoded picture data information, Base64 decoding byte array string
String Imgpath = UploadFile (filedata,licenename);//File upload operation, upload to server (here is stored in the Server project folder)

Boolean result = false;//Final upload success or failure mark

Custcheckinfo = new Customercheckinfo ();
Custcheckinfo.setcust_tax_code (Cust_tax_code);
Custcheckinfo.setphonenum (Phonenum);
Custcheckinfo.setupdate_time (New Date ()) (Df.format);

Boolean save_flag = Customerservice.saveregistcertinfo (custcheckinfo);//save path

Determine if a path exists in the database, and whether the file exists in the folder (to determine whether or not to upload a successful flag)
Boolean is_success = Issuccessupload (Licencename, Cust_tax_code, phonenum);
if (Save_flag && is_success) {
result = true;
}

If the document is uploaded successfully, it is recorded in the record form
if (result) {
Staterecordinfo record = new Staterecordinfo ();
Record.setcust_tax_code (Cust_tax_code);
Record.setphonenum (Phonenum);
RECORD.SETSTATE_ID (state_id);

Savestaterecord (record);//execute State save operation
}

System.out.println ("===result:" +result);
PrintWriter pw = Response.getwriter ();
Pw.print (result);
Pw.close ();
}

/**
* File Upload
* @param filedata
* @param fileName
* @return
*/
public string UploadFile (string filedata,string fileName) {
Construct a folder in your own project that holds the user's photos
String Imgpath = This.getservletcontext (). Getrealpath ("/uploads/");
If this folder does not exist, create a
File F = new file (Imgpath);
if (!f.exists ()) {
F.mkdir ();
}
Stitching file name, not existing on create
Imgpath = Imgpath + "/" + FileName + ". jpg";
f = new File (Imgpath);
if (!f.exists ()) {
F.mkdir ();
}

Log.info ("= = = The location of the file saved:" +imgpath);

Using BASE64 to decode picture file data
Base64decoder decoder = new Base64decoder ();
try {
Decrypts the picture data into a byte array via Base64 decryption
byte[] bytes = Decoder.decodebuffer (filedata);
Constructing a byte array input stream
Bytearrayinputstream Bais = new Bytearrayinputstream (bytes);
Reading data from an input stream
BufferedImage bi = imageio.read (Bais);
Write data into a picture file
Imageio.write (BI, "JPG", f);//regardless of what format picture is exported, no changes are required here
Bais.close ();
catch (IOException e) {
Log.error ("e:{}", E);
}
return imgpath;
}

/**
* Determine if successful upload
* @return
*/
public boolean issuccessupload (String licencename,string cust_tax_code,string phonenum) {
Boolean flag = false;
String Licencepath = "";//Document photo upload after successful path saved

Custcheckinfo = Customerservice.getcustomercheckinfo (Cust_tax_code, phonenum);
Licencepath = Custcheckinfo.gettax_regist_cert ();

To determine if the document path is not empty and exist in the uploaded folder, it indicates that the upload was successful
File F = new file (Licencepath);
if (Licencepath.length () >0 && f.exists ()) {
Flag = true;
}
return flag;
}



OK, here is all over, this is Html5+jquery+canvas call mobile phone camera function to achieve the full picture upload process, the total feeling of their own thinking some confusion, ah, slowly progress!


Plugin Address: Https://github.com/think2011/LocalResizeIMG

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.