Image upload-Download-delete some experience in image management 3-a complete solution for a single business scenario

Source: Internet
Author: User

This is a complete description of the picture upload complete solution, if there are bugs, follow-up.


First, the picture table
CREATE TABLE ' photo ' (  ' id ' bigint () unsigned not null auto_increment,  ' Bizid ' bigint (one) NOT null DEFAULT '-1 ' COMMENT ' business ID, such as Project ID ',  ' cover ' int (one) default ' 0 ' COMMENT ' 1: Yes, 0: not ',  ' sort ' int (each) default ' 0 ' COMMENT ' the smaller the more forward ',  ' url ' varchar ($) default null,  ' name ' varchar (255) default null COMMENT ' picture of the original filename ',  ' remark ' varchar (  255) Default NULL COMMENT ' Picture Memo ',  ' status ' int (one) default ' 0 ' COMMENT ' 0: Normal, 1: deleted, 2: temporary ',  ' type ' int (one) default ' 1 ' COMMENT ' 1: Project Data 2: ',  ' addtime ' datetime default NULL,  ' uptime ' datetime default NULL,  PRIMARY KEY (' I d ')) Engine=innodb auto_increment=102 DEFAULT charset=utf8 comment= ' user uploaded images ';




Key fields
ID: Database PRIMARY key
Bizid: The ID of the related business, such as the primary key ID for a project
Type: Types of related business, such as type=1 table name This picture is a project's
Status: The state of this picture, 0: normal state, 1: Deleted (now nothing, because the picture is physically deleted), 2: Temporary


Physical deletion of pictures is due to the lack of disk space easily.
The reason that should not be physically deleted is that it may be restored or other business needs in the future.


In the case of a tombstone, it is important to consider the physical deletion of "tombstone" and "temporarily uploaded spam pictures" separately.
In the case of physical deletion, you can consider merging.


Second, the image upload back-end code
@RequestMapping ("uploadimg") public void uploadimg (multiparthttpservletrequest request,httpservletresponse response , Long Bizid,integer type) {multipartfile file = request.getfile ("file"); Multipartfilevalidator validator = new Multipartfilevalidator (); Validator.setallowedcontenttypes (new String[] {" Image/jpeg "," Image/pjpeg "," Image/png "," Image/x-png "}); String path = null; String name = null;try {if (null! = File &&!file.isempty ()) {name = File.getoriginalfilename (); validator.validate (file);p ath = storefile (file); storeslavefile (file, path);} else {throw new Exception ("File is Empty");}} catch (Exception e) {e.printstacktrace (); Super.jsonfail (response, "image format is incorrect or larger than 1M"); return;} Long id = null;if (bizid! = null) {//Temporary picture saved photo photo = new photo ();p hoto.setname (name);p hoto.seturl (path);p hoto.setbiz ID (bizid);p hoto.setstatus (2);p hoto.settype (type); id = photoservice.add (photo);} Jsonobject jsonobject = new Jsonobject () jsonobject.put ("Code", ErrorCode.OK.getCode ()); Jsonobject.put ("Path ", path); Jsonobject.put (" name ", name), if (id! = NULL) {jsonobject.put (" id ", id);} Super.returnjsonobject (response, jsonobject);}


1. Storing pictures
2. Store photo Information
3. Return the ID, path and other information of the new image to the front end

Third, the front-end picture upload
function Bindsaveevent () {Console.log ("Bindsaveevent"), $ ("#save"). On ("click", Function () {var trs=$ (". tr"); var Photos = new Array (), $.each (Trs,function (i,n) {var tr = $ (trs[i]), var photo ={};//newid is the Idvar id=tr.attr ("id") in the database; var Newid=tr.attr ("newid");p hoto.id=newid;photo.cover=$ ("#" +id+ "-cover"). Val ();p hoto.sort=$ ("#" +id+ "-sort"). Val (); photo.remark=$ ("#" +id+ "-remark"). Val ();p hoto.url=$ ("#" +id+ "-img"). attr ("path");p hoto.name=$ ("#" +id+ "-name"). Val (); Console.log ("id=" +id);p Hotos[i]=photo;}); var json=json.stringify (Photos), Console.log ("id=${photovo.project.id}" + ", photos=" +json); $.ajax ({url: ' project/     Savephoto ', data:{ID: ${photovo.project.id}, Photos:json}, type: ' Post ', Cache:false,    Async:true, DataType: ' JSON ', success:function (data) {//alert (data.itemname);    NAMESTR = Data.itemname;    Console.log ("Data=" +data); }, Error:function () {alert ("Save picture Failed!       ");  }    }); });}


1. Using asynchronous upload, the ID of a picture information, name and other information, to the back-end save.
2. Pass in multiple graphs at once
There are "add" and "delete" buttons.
function Bindaddevent () {Console.log ("Bindaddevent"), $ ("#add"). On ("click", Function () {var strtemplate= ' <tr id= "{ Photo.id} "newid=" "class=" tr "> ' + ' <td><input id=" {photo.id}-name "type=" text "value=" "/></td>" + ' <td><select id= ' {photo.id}-sort ' class= ' sort ' > ' + ' <option value= ' 1 ' >1</option> ' + ' < Option value= "2" >2</option> ' + ' <option value= "3" >3</option> ' + ' <option value= "4" >4</ Option> ' + ' <option value= "5" >5</option> ' + ' <option value= "6" >6</option> ' + ' <option Value= "7" >7</option> ' + ' <option value= "8" >8</option> ' + ' <option value= "9" >9</option > ' + ' <option value= ">10</option> ' + ' <option value=" 0 ">0</option> ' + ' </select> </td> ' + ' <td><select id= "{photo.id}-cover" owner= "{photo.id}" ' + ' class= ' cover ' > ' + ' <option Value= "0" > No </option> ' + ' <option value= "1" > Yes </option> ' + ' </select></td> ' + ' < td><input type= "text" id= "{Photo.id}-remark" value= ""/></td> ' + ' <td><input type= "file" id= " {photo.id}-file "name=" "file" ' + ' style= "width:264px" onchange= "Uploadimg ({photo.id});" ></td> ' + ' <td><a id= ' {photo.id}- Del "owner=" {photo.id} "' + ' href=" javascript:; "class=" del "> Delete </a></td> ' + ' </tr> '; var photoid = New Date (). GetTime (), var html = strtemplate.replace (/{photo.id}/g,photoid), var tbody = $ ("#tbody"); Tbody.append (HTML) ; Console.log (HTML);//must be the newly generated object, rebind event binddelevent (); Bindcoverchangeevent ();});


Click the Add button to generate 1 more controls for uploading images.
Click the Delete button to delete an image upload space based on the ID.

Iv. Picture Preservation
public void Savephoto (httpservletresponse response, @RequestParam Long id,string photos) {list<photo> list= Jsonarray.parsearray (Photos, Photo.class);p Rojectservice.savephoto (id,list); super.jsonsucceed (response);}


ID is the id,photos of the owning item (JSON format) for all images in the front end

Save process:
public void Savephoto (Long ID, list<photo> list) {if (Collectionutils.isempty (list)) {Logger.error ("the Photo List is empty~ "); return;} The pictures in this project database, including all the states list<photo> DBList = Photodao.getphotolistbyprojectidallstatus (ID); Photobean Photobean = Handlephoto (list, dblist);//Theoretically, there is no longer an add Doadd (ID, Photobean.toadd);d oupdate (ID, photobean.toupdate);d odelete (ID, photobean.todelete);} DoUpdate and Dodelete batch update and bulk deletion method, very clear, no longer repeat. Photobean Structure class Photobean {//will be deleted, usually the public list<photo> todelete;//will be updated in the database, all in the database, Part of the latest content from the Web front-end public list<photo> toupdate;//will be added, because the uploading of images have been inserted, this time can be ignored//public list<photo> toadd;} Based on the front-end photo collection and the database photo collection, you get the photo collection that needs to be updated and deleted, there is no need to add the photo collection private Photobean Handlephoto (list<photo> List, List<photo> dblist) {Photobean bean = new Photobean ();//delete all, what pictures are not uploaded if (collectionutils.isempty (list)) { Bean.todelete = dblist;} All increase, generally in the 1th time/*if (Collectionutils.isempty (dblist)) {bean.toadd = list;} *///are not nullif (list! = null && dblist! = null) {//intersection, certainly not NULL, up to empty,id the same is common list<photo> commonlist = Listutils.retainall (list,            DBList);//2 intersection list<photo> toupdate = commonlist; Temporary picture in the database, the status needs to be changed to "normal" if (Collectionutils.isnotempty (toupdate)) {for (Photo p:toupdate) {p.setstatus (0);}} In list, no longer dblist in/*list<photo> toadd = new arraylist<photo> (); for (Photo p:list) {if (!dblist.contains (p) {Toadd.add (P);}} *///in DBList, not in list list<photo> todelete = new arraylist<photo> (); for (Photo p:dblist) {if (!list.contains (p)) {Todelete.add (P);}} Bean.toadd=toadd;bean.toupdate=toupdate;bean.todelete=todelete;} return bean;}



Override photo's Equals method, and the ID equals equal.

Five, written in the last
1. Because the individual likes to save the complete article in the local, does not like the picture, moreover Csdn's album also does not have the good use.
The articles I wrote seldom appeared in pictures, and we did not make a look.
2. Because picture management is part of the complete project, it is not convenient to upload the complete code.
First note down, the recent time, a separate project to open a demonstration picture upload.
3. Multiple images are uploaded separately because the images in the project can have many fields, such as notes remark, sorting sort, and so on.
If you only need a few fields such as URLs, you can use Baidu Webuploader multi-map upload components.
4. In the code, there is a front-end jquery, back-end Java code.
5. The physical storage of the picture can be stored locally, or it can be used Fastdfs.
6. In a few days to build a multi-figure demonstration project alone, I intend to simplify the point, save the picture without Fastdfs.
Do a separate project to demonstrate the use of Fastdfs.
7. People in need, their own reference to the integration of multi-map upload to Fastdfs.
8. Multi-image upload, really not a simple problem, at least spent 3 full working days.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Image upload-Download-delete some experience in image management 3-a complete solution for a single business scenario

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.