Javaweb implementation of the picture asynchronous upload, display in the foreground, and the binary to save to the database __javaweb

Source: Internet
Author: User

Through (ajaxfileupload.js) provides the Ajaxfileupload method, asynchronously uploads the picture, obtains in the backstage and transforms the binary system first to deposit in the session, succeeds returns the picture the ID to the Ajax, and through the jquery change img The address of SRC requests the binary resource of the picture.

Two uploads will overwrite the previous object saved in session, and make sure that the object in session is saved to the database. You can request a picture binary resource in the database by ID. code example spring+hibernate (front-end dependent jquery.js,ajaxfileupload.js) foreground HTML code

<%--picture shows Src as the default picture resource--% 
<%--picture upload--> <input id= "upfile" style= "Display:none"
Type= "File" name= "Upfile" >

Javascript

/**
         * Upload picture * *
         ("#upload"). On (' click ', Function () {
             $ ("#upfile"). Click ();
         });
       
        $ ("#upfile"). On ("Change", upfile);

        function Upfile () {
            $.ajaxfileupload ({
                secureuri:false,
                URL: "Upimg.aj",
                dataType: "JSON",
                / /fileelementid is an IMG tag ID
                fileelementid: ' Upfile ',
                success:function (data) {
                    ///Upload Success  change The SRC address of the label, the ID parameter is in fact not needed, mainly in order to refresh the IMG image resources.
                    $ ("#upload"). attr ("src", "getcurimg.aj?id=" +data.message);
                    Rebind the event to prevent two times of upload failure
                    $ ("#upfile"). On ("Change", upfile);
                }
            );
        
Backstage Controller

/** * Upload pictures to session * @param response * @param request/@RequestMapping (value = "/upimg.aj", method = Request method.post) public void upimgsession (httpservletresponse response, httpservletrequest request, HttpSession HttpSession) {//get picture Multiparthttpservletrequest Multipartrequest = (multiparthttpservletrequest) request;//According to the front desk n
Ame name gets uploaded file multipartfile img = multipartrequest.getfile ("Upfile");
		Defines an array that is used to save the uploaded file type List filetypes = new ArrayList ();
		Filetypes.add ("JPG");
		Filetypes.add ("JPEG");
		Filetypes.add ("BMP");
		Filetypes.add ("PNG");
		String fileName = Img.getoriginalfilename ();
		Long Id=null;
		Resultmodel Rm=null; if (!) ( Filename==null | | "". Equals (FileName)) {String extensionname = filename.substring (Filename.lastindexof (".")
			+1);
					if (Filetypes.contains (extensionname)) {//extension valid try{id = system.currenttimemillis ();
					Byte[] Content=img.getbytes ();
					String extension= "image/" +extensionname; Wjbdo wjbdo = new Wjbdo(Content,extension,id);
				Httpsession.setattribute ("Curimg", wjbdo);
				}catch (IOException e) {e.printstacktrace ();
			} rm=new Resultmodel (Id.tostring (), 1);
		}}else{rm=new Resultmodel ("Upload failed", 0);
		} Responsebuilder RB = new Responsebuilder ();

		try {rb.writejsonresponse (RESPONSE,RM);
		}catch (IOException e) {log.info ("IOException", e);  }/** * Request picture binary stream from session * @param response * @param requests/@RequestMapping (value = "/getcurimg.aj", method = requestmethod.get) public String getcurimg (httpservletresponse response,httpservletrequest request,httpsession
		httpSession) {Wjbdo wjbdo = (wjbdo) httpsession.getattribute ("curimg");
		Sets the file format Response.setcontenttype (wjbdo.getextension ());
			try{OutputStream out = Response.getoutputstream ();
			Out.write (Wjbdo.getcontent ());
		Out.close ();
		}catch (IOException e) {log.error ("Output picture stream failed", e);


	return null; /** * Confirm Save submit picture to Database * @param response * * * @RequestMapping(value = "/zcdj.aj", method = requestmethod.post) public void Zcdjsave (httpservletresponse response, HttpServletRequest R
		Equest,httpsession HttpSession) {//Save upload picture Wjbdo Wjbdo = (wjbdo) httpsession.getattribute ("curimg");
			if (wjbdo!=null) {zcmodel.setimg (Wjbdo.getid ());
		WJSERVICE.SAVEWJ (WJBDO); }
	}
Wjservice.java
Public interface Wjservice {
    boolean savewj (Wjbdo wjbdo);

    Wjbdo FindByID (Long ID);

    Boolean update (Wjbdo wjbdo);

    Boolean del (Long ID);
}
Wjserviceimpl.java
public class Wjserviceimpl implements Wjservice {

    Wjbdao Wjbdao;

    @Transactional Public
    Boolean SAVEWJ (Wjbdo wjbdo) {return
        wjbdao.save (WJBDO);
    }

    Public Wjbdo FindByID (Long ID) {return
         Wjbdao.findbyid (ID);
    }

    @Transactional Public
    boolean update (Wjbdo wjbdo) {
        wjbdao.attachdirty (wjbdo);
        return true;
    }

    @Transactional Public
    Boolean del (Long id) {
        wjbdo wjbdo = Wjbdao.findbyid (ID);
        if (wjbdo!=null) {
            wjbdao.delete (wjbdo);
            return true;
        }
        return false;
    }

    Public Wjbdao Getwjbdao () {return
        Wjbdao;
    }

    public void Setwjbdao (Wjbdao wjbdao) {
        This.wjbdao = Wjbdao;
    }
}

Wjbdao.java
public class Wjbdao extends hibernatedaosupport{private static final Logger log = Loggerfactory.getlogger (wjbdao.cl

    ASS); protected void Initdao () {//Do no} public boolean save (Wjbdo transientinstance) {Log.debu
        G ("Saving wjbdo instance");
            try{Serializable Serializable = Gethibernatetemplate (). Save (Transientinstance);
                if (serializable!= null) {Log.debug ("save Successful");
            return true;
            }}catch (RuntimeException re) {Log.error ("Save Failed", re);
        throw re;
    return false;
        public void Delete (Wjbdo persistentinstance) {log.debug ("deleting wjbdo instance");
            try {gethibernatetemplate (). Delete (persistentinstance);
        Log.debug ("delete successful");
            catch (RuntimeException re) {log.error ("Delete failed", re);
        throw re; }//Refresh SESSion//GetSession (). Flush ();
        Public Wjbdo FindByID (Long id) {log.debug ("getting WJBDO instance with ID:" + ID); try {wjbdo instance = (wjbdo) gethibernatetemplate (). Get ("Nju.software.fams.data.daoobje Ct.
            Wjbdo ", id);
        return instance;
            catch (RuntimeException re) {Log.error ("Get Failed", re);
        throw re;
        } public void Attachdirty (Wjbdo instance) {log.debug ("Attaching dirty Wjbdo instance");
            try {gethibernatetemplate (). Saveorupdate (instance);
        Log.debug ("Attach successful");
            catch (RuntimeException re) {Log.error ("Attach failed", re);
        throw re;
        } public void Attachclean (Wjbdo instance) {log.debug ("Attaching clean Wjbdo instance");
            try {gethibernatetemplate (). Lock (instance, lockmode.none);
    Log.debug ("Attach successful");    catch (RuntimeException re) {Log.error ("Attach failed", re);
        throw re;
        } public void Delbyid (long id) {log.debug ("Attaching clean Zcdo instance");
        Session session = Getsessionfactory (). Getcurrentsession (); Session.createquery ("Delete from Wjbdo where id=?").
    Setparameter (0,id). Executeupdate (); }
}
Wjbdo.java

@Entity @Table (name = "FAMS_WJB", schema = "Fixassetms") public class Wjbdo {private Long ID;
    Private byte[] content;

    /** * Extension/private String extension;
        Public Wjbdo (byte[] content, String extension, Long id) {this.content = content;
        this.extension = extension;
    This.id = ID;
    Public Wjbdo () {} @Id @Column (name = ' ID_WJ ') public Long getId () {return Id;
    public void SetId (Long id) {this.id = ID;
    @Column (name = "CONTENT") public byte[] GetContent () {return content;
    public void SetContent (byte[] content) {this.content = content;
    @Column (name = "EXTENSION") public String getextension () {return EXTENSION;
    } public void Setextension (String extension) {this.extension = extension; @Override public String toString () {return "wjbdo{" + "extension= '" + exteNsion + ' \ ' + ', id= ' + ID + '} '; }
}




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.