HTML5 + Canvas + jQuery call the mobile phone photo function to upload images (2)

Source: Internet
Author: User

HTML5 + Canvas + jQuery call the mobile phone photo function to upload images (2)

The previous article only talked about front-end operations. This article specifically involves Java background processing. The front-end submits Base64 encoded image data to the Java background through Ajax, and then receives and processes the data in Java, after Base64 Decoding of image data information, you can use a stream to upload image data information to the server for storage, and save the path and address of the image to the database.


You can click this link to view the processing of local compression uploads at the front end:

HTML5 + Canvas + jQuery call the mobile phone photo function to upload images (1)


Okay. You can paste the Code directly.


1. Front-end js Code:

$. Ajax ({async: false, // asynchronous cache: false, // whether cache 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

/*** Credential 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 image data, base64-decoded String imgPath = uploadFile (fileData, liceneName ); // perform the file upload operation and upload it to the server for storage (here it is uploaded to the project folder on the server) boolean result = false; // indicates whether the final upload is successful. custCheckInfo = new CustomerCheckInfo (); custCheckInfo. setCust_tax_code (cust_tax_code); custCheckInfo. setPhonenum (phoneNum); custCheckInfo. setUpdate_time (df. format (new Date (); boolean save_flag = customerService. saveRegistCertInfo (custCheckInfo); // save path // determine whether the path in the database exists and whether the file in the folder exists (the flag for determining whether the upload is successful) boolean is_success = isSuccessUpload (licenceName, cust_tax_code, phoneNum); if (save_flag & is_success) {result = true ;}// if the credential is uploaded successfully, it is recorded in the record table if (result) {StateRecordInfo record = new StateRecordInfo (); record. setCust_tax_code (cust_tax_code); record. setPhonenum (phoneNum); record. setState_id (state_id); saveStateRecord (record); // save execution status} 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) {// create a folder for storing user photos in your project String imgPath = this. getServletContext (). getRealPath ("/uploads/"); // if this folder does not exist, create a File f = new File (imgPath); if (! F. exists () {f. mkdir ();} // name of the spliced file. If the file does not exist, create imgPath = imgPath + "/" + fileName + ". jpg "; f = new File (imgPath); if (! F. exists () {f. mkdir ();} log.info ("=== file storage location:" + imgPath ); // use BASE64 to decode the image file data. BASE64Decoder decoder = new BASE64Decoder (); try {// use Base64 to decrypt the data, decrypts the image data into a byte array byte [] bytes = decoder. decodeBuffer (fileData); // constructs ByteArrayInputStream bais = new ByteArrayInputStream (bytes); // reads data from the input stream BufferedImage bi = ImageIO. read (bais); // write data into the image file ImageIO. write (bi, "jpg", f); // no matter what format image is output, you do not need to change bais here. close ();} catch (IOException e) {log. error ("e :{}", e);} return imgPath ;}

/*** Determine whether the upload is successful * @ return */public boolean isSuccessUpload (String licenceName, String cust_tax_code, String phonenum) {boolean flag = false; String licencePath = ""; // The saved path custCheckInfo = customerService after the credential image is uploaded successfully. getCustomerCheckInfo (cust_tax_code, phonenum); licencePath = custCheckInfo. getTax_regist_cert (); // if the File f = new File (licencePath); if (licencePath. length ()> 0 & f. exists () {flag = true;} return flag ;}



Okay, now it's all over. This is the process of using the HTML5 + jQuery + Canvas to call the mobile phone camera function to upload images. I always feel a bit confused. Well, keep improving!

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.