Java allows you to upload images to the server, read uploaded images, and upload java images.

Source: Internet
Author: User

Java allows you to upload images to the server, read uploaded images, and upload java images.

You can upload portraits on many websites. You can select your favorite images as portraits and upload them locally. The uploaded portraits will be displayed at next login, how is this implemented?

 

Next, let's talk about my implementation process (just my personal idea, but it's not clear how the actual website is implemented)

Implementation ideas:

Tools: MySQL and eclipse

First, two tables are created in MySQL. One t_user table is used to store personal information such as user names and passwords,

A t_touxiang table is used to store the path of uploaded images on the server, as well as the image name and user ID,

The User id in the T_touxiang table corresponds to the id in t_user.

T_user table SQL:

DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` (  `id` int(10) NOT NULL AUTO_INCREMENT,  `username` varchar(20) NOT NULL,  `password` varchar(255) NOT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `username` (`username`)) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;

T_touxiang table SQL:

DROP TABLE IF EXISTS `t_touxiang`;CREATE TABLE `t_touxiang` (  `id` int(10) NOT NULL AUTO_INCREMENT,  `image_path` varchar(255) DEFAULT NULL,  `user_id` int(11) DEFAULT NULL,  `old_name` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`),  KEY `img_user` (`user_id`),  CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

First, write an UploadServlet. java file to process the upload of an image file, and store the image path, image name, and other information in the t_touxiang data table. The Code is as follows:

@ WebServlet ("/UploadServlet. do ") public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L; protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// determine whether the upload form is multipart/form-data Type HttpSession session = request. getSession (); User user = (User) session. getAttribute ("user"); // put the User object into the session during login // If (ServletFileUpload. isMultipartContent (request) {try {// 1. create a DiskFileItemFactory object and set the buffer size and the temporary file directory DiskFileItemFactory factory = new DiskFileItemFactory (); // System. out. println (System. getProperty ("java. io. tmpdir "); // default Temporary Folder // 2. create a ServletFileUpload object and set the size limit of the uploaded file. ServletFileUpload sfu = new ServletFileUpload (factory); sfu. setSizeMax (10*1024*1024); // The unit of byte cannot exceed 10 M 1024 byte = // 1kb 1024kb = 1 M 1024 M = 1Gsfu. setHeaderEncoding ("UTF-8"); // 3. // call ServletFileUpload. the parseRequest method parses the request object to obtain a List object that stores all the uploaded content. @ SuppressWarnings ("unchecked") List <FileItem> fileItemList = sfu. parseRequest (request); Iterator <FileItem> fileItems = fileItemList. iterator (); // 4. traverse the list. Each iteration of A FileItem object calls its isFormField method to determine whether the object is being uploaded while (fileItems. hasNext () {FileItem fileItem = fileItems. next (); // normal form element if (fileItem. isFormField () {String name = fileItem. getFieldName (); // name attribute value String value = fileItem. getString ("UTF-8"); // name pair Value System. out. println (name + "=" + value);} // The else {String fileName = fileItem element of the file to be uploaded <input type = "file">. getName (); // file name System. out. println ("original file name:" + fileName); // Koala.jpg String suffix = fileName. substring (fileName. lastIndexOf ('. '); System. out. println ("Extension:" + suffix );//. jpg // new file name (unique) String newFileName = new Date (). getTime () + suffix; System. out. println ("new file name:" + newFileName); // imag E \ 1478509873038.jpg// 5. call the write () method of FileItem and write the File file = new File ("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName); System. out. println (file. getAbsolutePath (); fileItem. write (file); // 6. call the delete () method of FileItem to delete the temporary file fileItem. delete ();/** Note 1 When storing data to the database. save the source file name Koala.jpg 2. save the relative path * image/1478509873038.jpg **/if (user! = Null) {int myid = user. getId (); String SQL = "INSERT INTO t_touxiang (image_path, user_id, old_name) VALUES (?,?,?) "; Int rows = JdbcHelper. insert (SQL, false, "touxiang/" + newFileName, myid, fileName); if (rows> 0) {session. setAttribute ("image_name", fileName); session. setAttribute ("image_path", "touxiang/" + newFileName); response. sendRedirect (request. getContextPath () + "/upImage.html");} else {}} else {session. setAttribute ("loginFail", "Log on"); response. sendRedirect (request. getContextPath () + "/login.html") ;}}} catch (FileUploadException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace ();}}}}

After uploading images and writing them to the database, the image path is sent to the HTML interface through session.

 

<! DOCTYPE html> 

So far, Image Upload databases and local servers have been implemented. How can I display personal information and uploaded portraits on the HTML interface?

 

First, define a PersonServlet class to read the database content and send it to the HTML interface.

The Code is as follows:

@ WebServlet ("/persons. do ") public class PersonServlet extends HttpServlet {private static final long serialVersionUID =-800352785988546254L; protected void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// determine whether the upload form is multipart/form-data Touxiang tx = null; HttpSession session = request. getSession (); User user = (User) session. getAttribute ("user "); // Put the User object into the session if (user! = Null) {int myid = user. getId (); String SQL = "SELECT id, image_path, old_name FROM t_touxiang WHERE user_id =? "; ResultSet rs = JdbcHelper. query (SQL, myid); String uSQL =" SELECT username, password FROM t_user WHERE id =? "; ResultSet urs = JdbcHelper. query (uSQL, myid); System. out. println ("My personal id is:" + myid); final List <Touxiang> touxiang = new ArrayList <> (); try {if (rs. next () {tx = new Touxiang (); tx. setId (rs. getInt (1); tx. setImage_path (rs. getString (2); tx. setOld_name (rs. getString (3); touxiang. add (tx);} if (urs. next () {user. setUsername (urs. getString (1); user. setPassword (urs. getString (2); user. setTouxiang (touxiang) ;}} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} session. setAttribute ("user", user); System. out. println ("My id:" + myid); response. sendRedirect (request. getContextPath () + "/person.html ");}}}

The Code is as follows:

<Div> <form action = "UploadServlet. do "method =" post "enctype =" multipart/form-data "> <div> <a href =" $ path/upImage.html "> change Avatar </a> </div> # foreach ($ ut in $ user. getTouxiang ()  # end <div> my avatar: </div> <div> my name: $ user. getUsername () </div> <a href = "$ path/myAnswer. do "> my answers </a> </div> <a href =" $ path/myQuestion. do "> my questions </a> </div> </form> </div>

So far, a Java-based Avatar upload server stores the path in MySQL and basically implements the functions read from the HTML interface. You can select some plug-ins to perform operations such as processing the Avatar before uploading it. The basic functions are simply implemented here.


Supplement

For image uploading, the most basic functions are simply implemented using Servlet, which only provides ideas. If spring and other frameworks are used, it is easier to encapsulate image uploads.

It is easier to upload images in the background, but the headache is that the native button for uploading images is ugly. We recommend the two practical upload controls, which should be nice.


1. You can upload multiple images in H5. You can click and drag to upload images, which is like this:

Basic usage and: http://blog.csdn.net/weixin_36380516/article/details/70352689


2. jQuery image cropping plug-in, which is about long



It not only provides upload, cropping, and other functions, but also makes the UI beautiful,

Address: http://www.jq22.com/jquery-info318

Finally, we recommend a Public Account "Java Zhiyin", push Java-related technical articles, and sort them by system. It is also very good to look at the time!

Related Article

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.