Javaweb-----------Simple Album Management

Source: Internet
Author: User

Album Management

This is just a small album management, the main implementation of the function: to achieve the image upload , Unified browsing , single download , single deletion , can only delete their own uploaded files.

A single explanation of each feature is now:

Uploading of images The uploading of images is very clear in the previous blog. Click to open the link;in this album management, it is not a single file transfer, but also need to involve a lot of parameters for the use of other functional modules
<span style= "FONT-SIZE:24PX;"  >//upload files generally use the outside of the Apache upload Toolkit/* * We need to put the uploaded files under the specified folder * to get the file's information file name to store the folder (beat) Uuid--dir * Solve the Chinese problem store filename uuid.jpg * Everyone has their rights IP * upload Time dt * File original real name Relname * Photo Description desc * File extension ext * Upload a picture above need so many letters The value object "VO" package uses scrambled folder storage for better performance. </span> 
<span style= "FONT-SIZE:24PX;" > */request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out=response.getwriter ();//Read files using Apache two packages//temporary storage directory file F =new file ("F:/ex/temp");// directory where temporary files are stored diskfileitemfactory dff=new diskfileitemfactory (1024*1024*20, f);//Allow temporary storage file size of 20m// Tools for parsing files servletfileupload SF =new servletfileupload (DFF); Sf.setsizemax (1024*1024*50);// The allowable storage capacity is 50msf.setfilesizemax (1024*1024*20);//The maximum capacity of a single file is 20MString Path=getservletcontext (). Getrealpath ("/upfile") ;//The path to the disk where the file was obtained--"storage location photo p =new photo (); InputStream in=null;//copy stream requires a Boolean boo=false; Fileitem f0=null;//used to delete temporary files try {list<fileitem> list=sf.parserequest (request); for (Fileitem ff:list) {</span >
<span style= "FONT-SIZE:24PX;" >//in front of all is the same as the previous one said, the specific statistical parameters is from here to start. </span>
<span style= "FONT-SIZE:24PX;" >f0=ff;if (Ff.isformfield ()) {//This is a description of the contents of string name=ff.getstring ("Utf-8");//UTF-8 encoding to read P.SETDESC (name);//1 The description of the file}else{string name=ff.getname ();//Get the contents of the file in this box---> the entire picture of the directory//system.out.println ("name:" +name); String id=utilsfactory.getuuid ();p. SetId (ID);//6string dirs=utilsfactory.getdir (ID);// Get the folder directory----P.setdir (dirs) with UUID one by one, the directory P.setdt (Utilsfactory.getdate ()) after//2 upset;//3 time string relname= Name.substring (Name.lastindexof ("/") +1);p. Setrelname (relname);//4 file real name string ext=name.substring ( Name.lastindexof (".")); P.setext (ext);//5 file extension P.setip (REQUEST.GETREMOTEADDR ());//7 Ipboo =mydao.add (P);//Save to XML file if (Boo) {//Save successful Path= path+ "/" +p.getdir (); File F1 =new (path);//Determine if the stored path exists, create if (!f1.exists ()) {F1.mkdirs ()}, and do not exist. In=ff.getinputstream (); Fileutils.copyinputstreamtofile (in,new File (path+ "/" +p.getid () +p.getext ()));}}} catch (Fileuploadexception e) {boo=false;} Finally{if (f0!=null) {f0.delete ();//delete temporary file}}</span> 
uploading in addition to the statistical parameters, we need to store the data in the XML file and also need to store the picture. And so on when browsing the unified view. :


Unified Browsingbrowsing basically is all the data inside the XML file, read it out, and then read it in a unified display. Encapsulated in a list, encapsulating all of the photo data in the list collection
Queries all objects and then encapsulates a List object back to the front-end public static list<photo> GetAll () {list<photo> list=new Arraylist<photo > ();D ocument Dom =documentfactory.getdocument (); Element Root=dom.getrootelement (); Iterator it=root.elementiterator ();//This is the root node walker while (It.hasnext ()) {Element e= ( Element) It.next ();//Find node photo p =new photo ();//Each photo address is not the same, so each new space must be opened P.setdesc (E.attributevalue ("desc"));// File descriptor P.setdir (E.attributevalue ("dir"));//File Directory P.setdt (e.attributevalue ("DT"));//Time P.setext (E.attributevalue (" Ext "))///File extension P.setid (E.attributevalue (" id ")),//uuid generated Idp.setip (e.attributevalue (" IP "));p. Setrelname ( E.attributevalue ("Relname")); List.add (P);} return list;}

Specific code:
Browsing the album requires reading all the files. Requires one by one to read, so you need to read all the XML files Response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding ("Utf-8"); PrintWriter out = Response.getwriter (); Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ") out.println (" <HTML> "); Out.println (" < Head><title>a servlet</title>Effect:

Single DownloadThe download has been made very clear in previous uploads and downloads. Click to open linkyou need to be aware of the downloaded code: you need to set the transfer of the corresponding header and file name
For the download file needs primarily  need to let the browser know the  setting header * Response.setcontenttype ("application/force-download");//Set the corresponding header, tell the browser this is the download file * The second is to set the filename  * response.setheader ("content-disposition", "attachment;filename=", "+relname+" ");// The download is the original file name shown there

Here is the specific code:
Response.setcontenttype ("Application/force-download");//Set the appropriate header to tell the browser that this is the download file request.setcharacterencoding ("Utf-8") ; String id=request.getparameter ("id"); Photo P=mydao.getsingalbyid (ID);//Get the object to download by ID//write real name if (p!=null) {String relname1=p.getrelname (); String Relname=urlencoder.encode (relName1, "Utf-8"); Response.setheader ("Content-disposition", "attachment; Filename= ' "+relname+" ");//download is over there the original file name is displayed outputstream out =response.getoutputstream ();//The path to write the file requires//paths string path="/ upfile/"+p.getdir () +"/"+p.getid () +p.getext (); String path1 =getservletcontext (). Getrealpath (path); System.out.println (path1);//Detection InputStream in=new FileInputStream (path1); byte[] B=new byte[1024];int len =0;while (( Len=in.read (b))!=-1) {out.write (b, 0, Len);}} Else{response.setcontenttype ("Utf-8"); PrintWriter PW =response.getwriter ();p w.write ("file does not exist cannot be downloaded");}}




Deleting files the techniques used to delete files are relative to other functionsto match ip,id so that you can use permissions when deleting
//delete photo public static map<string, object> Deletebyid (String ip,string ID) {map< String, object> map =new hashmap<string, object> ();D ocument Dom =documentfactory.getdocument (); Element ele= (Element) Dom.selectsinglenode ("//photo[@id = '" +id.trim () + "']"),//xpath use if (ele==null) {map.put (" Success ", false); Map.put (" msg "," deleted "); return map; Else{string tempip=ele.attributevalue ("IP"), if (!tempip.equals (IP)) {map.put ("success", false), Map.put ("MSG", " You cannot delete photos of others "); return map;} Else{map.put ("Success", true);//After the successful access, the data is divided into a value object, return to the logical layer of our direct deletion, just the node inside the XML file is deleted, but the file has been stored is not deleted photo p =new photo ( );p. SetId (ID);p. Setext (Ele.attributevalue ("ext"));p. Setdir (Ele.attributevalue ("dir")); Map.put ("Photo", p);// Real data Delete ele.getparent (). Remove (Ele);D ocumentfactory.save (); return map;}} 
Request.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter Out=response.getwriter (); String ID =request.getparameter ("id");//The message passed from the client string IP =request.getremoteaddr (); map<string, object> map =mydao.deletebyid (Ip,id), if (Map.get ("Success"). Equals (False)) {//This is the deletion of unsuccessful out.print ( The message is: "+map.get (" Success "));} Else{photo p = (photo) Map.get ("photo");//Delete the file according to the filename and path inside the photo Path=getservletcontext (). Getrealpath ("Upfile") ; String filename=path+ "/" +p.getdir () + "/" +p.getid () +p.getext ();//The path to the file includes the filename System.out.println (filename); File  f=new file (filename), if (F.exists ()) {System.out.println (F.getname ()); F.delete ();//delete file}} Response.sendredirect ("Lookphoto");//redirect to display page}
Download link for entire project Click to open linkI am in the study, just learned this knowledge point. This technology may be very backward, I will learn the new technology, so that their own growth. If you need this simple program, you can find me directly.

Javaweb-----------Simple Album Management

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.