[project build five]babasport Ajax image upload and Fastdfs starter Case.

Source: Internet
Author: User

Today to start to write the function of uploading pictures, now the image upload is to emphasize the upload after the completion of the immediately echo and the page does not refresh, here exactly how to do it? ajax, of course, But Ajax can't submit a form, and here we have a plugin: jquery.form.js
The remaining one is fastdfs, so what is fastdfs?
Fastdfs is an open source lightweight Distributed file system consisting of three parts of the tracking server (tracker server), Storage server (storage server) and client (clients), which mainly solves the problem of massive data storage. It is particularly suitable for online services with medium and small files (recommended range: 4KB < file_size <500mb).

Here are just a few of the advantages of fastdfs:

Solves the problem of mass storage and load Balancing. Especially suitable for file-based online services, such as photo album sites, video sites and so On.

The FASTDFS server has two roles: tracker (tracker) and storage node (storage). The tracker mainly does the dispatching work, and the function of load balancing on the ACCESS.
For more details, refer To: http://blog.chinaunix.net/uid-20196318-id-4058561.html

one, Development Examples
0, using Fastdfs:
First you need to install and configure Fastdfs under linux, which is not mentioned Here.
First look at the introduction of the Fastdfs jar Package:

To view the fdfs_client.conf configuration file:

We find that the settings here are not what we want, so what should we do? We need to cover one part of our project:

The configuration file contents are as Follows: (need to configure Tracker_server Here)

1 # Connect Timeout in seconds2 # Default value is 30s3 connect_timeout=304 5 # Network timeout in seconds6 # Default value is 30s7 network_timeout=608 9 # The base path to store log filesTen Base_path=/home/fastdfs one  a # tracker_server can ocur more than once, and tracker_server format is - # "host:port", host can be hostname or IP address - tracker_server=192.168.200.128:22122 the #tracker_server =192.168.101.4:22122 -  - #standard Log level as syslog, case insensitive, value list: - # # # Emerg for emergency + # # Alert - # # # Crit for critical + # # Error a # # # Warn for warning at # # Notice - # # Info - # # Debug - Log_level=info -  - # If Use connection pool in # Default value is False - # since V4.05 to Use_connection_pool = False +  - # Connections whose the idle time exceeds this time'll be closed the # Unit:second * # Default value is 3600 $ # since V4.05Panax Notoginseng connection_pool_max_idle_time = 3600 -  the # If load Fastdfs parameters from Tracker server + # since V4.05 a # Default value is False the Load_fdfs_parameters_from_tracker=false +  - # If Use storage ID instead of IP address $ # Same as tracker.conf $ # valid only if Load_fdfs_parameters_from_tracker is False - # Default value is False - # since V4.05 the use_storage_id = False - Wuyi # Specify storage IDs filename, can use relative or absolute path the # Same as tracker.conf - # valid only if Load_fdfs_parameters_from_tracker is False wu # since V4.05 - storage_ids_filename = storage_ids.conf about  $  - #HTTP Settings - http.tracker_server_port=80 -  a #use "#include" directive to include HTTP other settiongs +# #include http.conf


1. Add input tag to JSP to upload image

Here is a hidden domain field is imgurl, here is to save the uploaded image after the successful return of the image address, in the submission of the entire form, the URL is saved to the database, in the list.jsp directly take the URL to echo the image Data.

2, Add the Upload JS code:

The Ajaxsubmit method is used here, when we upload a picture, we actually submit the form, and then we use the Uploadpic method in the Uploadpiccontroller to process the sent Request.


3, build UploadPicController.cs to parse uploadpic.do request
Controller Layer:
Uploadcontroller.java:

1*Upload Image2*/3 @Controller4@RequestMapping (value= "/upload")5  public classUploadcontroller {6  7 @Autowired8     PrivateUploadservice uploadservice;9     Ten     //Upload Image Brand one@RequestMapping (value= "/uploadpic.do") a      public voidUploadpic (@RequestParam (required=false) Multipartfile pic, HttpServletResponse Response)throwsexception{ -          -         //Java Interface Connection Fastdfs theString Path =uploadservice.uploadpic (pic.getbytes (), pic.getoriginalfilename (), pic.getsize ()); -          -         //path:group1/m00/00/01/wkjigfwoyc6appjaaad-qk29i78248.jpg -         //Url:http://192.168.200.128(the IP Address of the Linux virtual Machine) +String url = constants.img_url +path; -          +         //JSON Tool class aJsonobject Jo =NewJsonobject (); atJo.put ("url", url); -Jo.put ("path", path); -          -         //return JSON -Response.setcontenttype ("application/json;charset=utf-8"); - response.getwriter (). Write (jo.tostring ()); in     } -}

The URL is written back to the front end in JSON format so that the parameters can be received and the picture echoed in the Ajax Request.

Service Layer:
Uploadserviceimpl.java:

1 /*2 * Upload Images3  */4@Service ("uploadservice")5  public classUploadserviceimplImplementsUploadservice {6 7     //Upload8      publicString Uploadpic (byte[] pic, String name,LongSize) {9         returnfastdfsutils.uploadpic (pic, name, size);Ten     } one}

Common tool Class:
FastDFSUtils.cs

1 /*2 * Upload Fastdfs images3  */4  public classFastdfsutils {5 6      public StaticString Uploadpic (byte[] pic, String name,LongSize) {7String Path =NULL;8         //files under classpath spring9Classpathresource resource =NewClasspathresource ("fdfs_client.conf"); Ten         Try { oneClientglobal.init (resource.getclassloader (). getresource ("fdfs_client.conf"). GetPath ()); a             //Customer Service Side -Trackerclient trackerclient =Newtrackerclient (); -Trackerserver Trackerserver =trackerclient.getconnection (); the              -             //Connecting little brother -StorageClient1 storageClient1 =NewStorageClient1 (); -             //extension, get the extension, Apach the public method is already in the common Package. +String Extension =filenameutils.getextension (name); -             //Set picture meta information +namevaluepair[] meta_list =NewNamevaluepair[3]; ameta_list[0] =NewNamevaluepair ("filename", name); atmeta_list[1] =NewNamevaluepair ("fileext", extension); -meta_list[2] =NewNamevaluepair ("filesize", string.valueof (size)); -             //upload and return path -Path =storageclient1.upload_file1 (pic, extension, meta_list); -}Catch(Exception E) { -             //TODO auto-generated Catch block in e.printstacktrace (); -         } to         returnpath; +     } -}

Here is the core method of fastdfs, here will tracker analogy to eldest brother, will storage analogy into younger Brother. and add some meta information to this image, and finally call Upload_file1 to upload the image to the image server and return to Path.
This is how the whole development process works, and it's a great way to get a better look at the review later.



[project build five]babasport Ajax image upload and Fastdfs starter Case.

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.