Ext4 + servlet + HTML5 allows you to obtain the File Upload progress, local preview, and drag/Drop File Upload album instances in real time.

Source: Internet
Author: User

This evening, I spent a few hours preparing an album, similar to uploading files in the QQ space. However, I used ext + HTML5 and other new technologies to upload files with servlet. There are several features:

  • Drag/Drop File Upload
  • Get upload progress in real time
  • Local Preview
  • Combined with ext
After talking about this, I 'd like to paste a few pictures for you !! When the image is dragged in a window without any operation, the system prompts to drag the image to the specified area. This is a local preview generated, the detailed information is displayed after the upload is successful. This may be the local reason. The upload is complete at once, and the percentage is not shown. This is probably what it looks like! The following describes the implementation: first, build the ext window:
// Create an album window var win = ext. create ('ext. window. window ', {Title: 'ext album', width: 700, height: 400, iconcls: 'ablum ', layout: 'fit', plain: false, items: [view], buttons: [{text: 'upload', // upload button handler: Upload, iconcls: 'upload'}, {text: 'clear', Handler: function () {store. removeall () ;}, iconcls: 'clear'}]}); win. show ();

Create a container like an image:

// Create an image data model. The data source must be var photomodel = ext. define ('imagemodel', {extend: 'ext. data. model ', fields: [{Name: 'name'}, {Name: 'type'}, {Name: 'SIZE', type: 'float'}, {Name: 'lastmod', type: 'date', dateformat: 'timestamp'}, {Name: 'file'}, {Name: 'src'}]}); // create the data source var store = ext. create ("Ext. data. store ", {model: photomodel}); var ddtip; // image prompt template var tiptpl = 'name: {0} <br/> '+' type: {1} <br/> '+' size: {2} <br/> '+' modification time: {3} <br/> '// create the image storage container var view = ext. create ('ext. view. view ', {store: store, // specify the data source TPL: [// set the display template' <TPL for = ". "> ',' <Div class =" Thumb-wrap "id =" {name} "> ', '<Div class = "Upload-Progress"> 0% </div> ', '<Div class = "Thumb">  </div> ', '<span> {name} </span> </div>', '</TPL> ', '<Div class = "X-clear"> </div>'], style: {backgroundcolor: '# ffff', fontfamily: ''}, multiselect: True, trackover: True, overitemcls: 'x-item-over', itemselector: 'div. thumb-wrap ', emptytext: 'No shown photos', autoscroll: True, listeners: {'afterrender': function () {// create a user to drag and drop the prompt ddtip = view. el. createchild ({Tag: 'div ', CLS: 'dd-tip', HTML: 'please drag the image here'}); // The floating prompt Ext. create ('ext. tip. tooltip ', {target: View. el, delegate: View. itemselector, trackmouse: True, renderto: ext. getbody (), anchor: 'right', listeners: {beforeshow: function (TIP) {var record = view. getrecord (tip. triggerelement); tip. update (ext. string. format (tiptpl, record. get ('name'), record. get ('type'), record. get ('SIZE'), ext. date. format (record. get ('lastmod '), 'y, M, D, H, I ')));}}});}}});

Drag and drop events on the Add listener page:

// Add an event to the body. If there is a drag, the system prompts you to drag the event to the specified area Ext. getbody (). on ('dragover', function (e) {ddtip. show () ;}); // hide the prompt message Ext. getbody (). on ('dragleave ', function (e) {ddtip. hide () ;}); // hide the prompt information view when you drag it to a specified area. el. on ('dragenter', function (e) {e. stoppropagation (); E. preventdefault (); ddtip. hide (); view. el. highlight () ;}); // when the user leaves the specified area, a prompt view is displayed. el. on ('dragleave ', function (e) {e. stoppropagation (); E. preventdefault (); ddtip. show () ;}); // Key !! The Time View is triggered when you drag and drop a file. el. dom. ondrop = function (e) {e. stoppropagation (); E. preventdefault (); ddtip. hide (); // hide the prompt information // process the file process (E. datatransfer. files );};

Process the files dragged by the user:

Function process (Files) {var COUNT = 0; For (VAR I = 0; I <files. length; I ++) {var file = files [I]; // This file object // creates a photo data instance, saves the name, size, type, modification date, file and other information var photo = ext. modelmanager. create ({Name: file. filename, size: file. filesize, type: file. type, file: file, lastmod: file. lastmodifieddate}, photomodel); // Add it to the data source, which may easily change the store. add (photo); // obtain the preview var reader = new filereader () through the filereader object; // The callback reader executed after the read is complete. onload = (function (p) {return function () {count ++; // store the obtained image data in base64 format. data. src = This. result; If (COUNT = files. length) {// after all the images are loaded, render the Image view. refresh () ;}}) (photo); // The JS closure principle is used in this part. // read the image reader. readasdataurl (File );}}

Upload method:

Function upload () {// execute the Upload store. each (function (photo) {// traverses data from the data source var progress = ext. get (view. getnode (photo )). down ('div. upload-SS '); // displays the progress information progress. show (); var xhr = new XMLHttpRequest (); // initialize xmlhttprequestxhr. open ('post', 'upload', true); xhr. upload. onprogress = function (p) {// Add data upload progress, get real-time upload progress return function (e) {If (E. lengthcomputable) {var percentage = math. round (E. loaded * 100)/E. total ); Progress. update (percentage + "%") ;}}( progress); xhr. upload. onload = function (p) {// return function (e) {progress. update ("Upload successful! ") ;}} (Progress); var FD = new formdata (); // It is critical to initialize a formdata file and send the file to the backend FD. append ("file", photo. data. file); xhr. send (FD );});}

Servlet code for file upload:

@SuppressWarnings("unchecked")public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String path = request.getSession().getServletContext().getRealPath("\\upload");DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {List<FileItem> list = (List<FileItem>) upload.parseRequest(request);for (FileItem fileItem : list) {String fileName = fileItem.getName();File file = new File(path + "\\" + fileName);fileItem.write(file);fileItem.delete();}} catch (Exception e) {e.printStackTrace();}}

In this way, this album instance is complete!
------------------------------------------------------------------------------ Split line ---------------------------------------------------------------------------------
Updated on May 14:

  • Added the function of selecting files through the resource manager.
  • Fixed the upload progress display bug.
  • Add a shortcut menu
  • Upload changed to upload all items and upload selected items
  • Added the image browser function.
  • The image browser supports dragging, double-clicking to maximize/restore, and changing the size.
  • The image browser supports navigation of images in the data source.
  • Image browser image enlargement and reduction
Due to the rush of updates, the quality of the written code is not very high. The image browser should be encapsulated into an object, and the image rotation function is not completed. These work should be done by the big guy himself. The code for image rotation is available on the Internet. Texture for everyone:
Click the Add button to select an object.
Right-click photo menu
Image Viewer. Double-click a photo to start it. Supports image amplification and navigation! Are you sure you can only run it in Chrome? There is a mistake in running it in Firefox. You are not too lazy to call it! The source code will be placed in the Download Area, but csdn has a delay and cannot find the link!
Split line -------------------------------------------------------------------------------------------
We recommend that you use the latest Google Chrome browser.
What else can ext do? There is nothing unexpected. You can't do it anymore. Go to the terminal !! Hate ie !!
Http://download.csdn.net/detail/leecho571/4292639 download! Http://download.csdn.net/detail/leecho571/4657009)
Finally, small ads are laid,
Reading comments is a virtue, and your comments are my greatest motivation !!

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.