H5 upload the video to the server, save to the specified location, save the URL to the database, and then display it in a specific format

Source: Internet
Author: User
Tags create directory

First, the video is uploaded to the server and saved to the specified location.

Try one of the most reliable of n methods:

Http://www.cnblogs.com/xdp-gacl/p/4200090.html

Second, the URL is saved to the database

1. Create a new JDBC package in the project

New class

Package Jdbc;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.preparedstatement;import Java.sql.resultset;import Java.sql.sqlexception;import Java.util.properties;public class JdbcUtil {private static String driver;private static string url;private static string user;private static string password;private static Propertie S pr=new Properties ();p ublic jdbcutil () {}static {try {pr.load (JdbcUtil.class.getClassLoader (). getResourceAsStream (" Dbconfig.properties "));d River=pr.getproperty (" Driver "); Url=pr.getproperty (" Dburl "); User=pr.getproperty (" User ") ;p assword=pr.getproperty ("password"); Class.forName (driver);} catch (Exception e) {e.printstacktrace ();}} public static Connection getconnection () throws Sqlexception{return drivermanager.getconnection (Url,user,password);} public static void Free (ResultSet rs,preparedstatement st,connection conn) {try {if (rs!=null) Rs.close ();} catch ( SQLException e) {e.printstacktrace ();} Finally{try {if (st!=null) St.close ();} catch (Sqlexception E2) {e2.printstacktrace ();} Finally{try {if (conn!=null) Conn.close ();} catch (SQLException E3) {e3.printstacktrace ();}}}} public Boolean Write (String s) throws Sqlexception{int n=0; Connection conn=getconnection (); PreparedStatement Ps=null;try {ps=conn.preparestatement (s); n=ps.executeupdate (); if (n!=0) return true;} catch ( Exception e) {e.printstacktrace ();} Finally{free (NULL, PS, conn);} return false;}}

2, SRC under a new

Dbconfig.properties
driver=com.mysql.jdbc.driverdburl=jdbc\:mysql\://localhost\:3306/app?useunicode=true&characterencoding= utf-8user=rootpassword=123456

3. Create a new package bean (entity Class) You might want to deposit more than just a URL, like the general entity class, the Getter setter has a parameter-free constructor.

Slightly

4. Create a new DAO package

New class

Package Dao;import Java.sql.sqlexception;import Bean. Resourse;public interface Resoursedao {public boolean insert (Resourse R) throws SQLException;}

5. Daoimpl Bag

New class

Package Daoimpl;import Java.sql.sqlexception;import Bean. Resourse;import DAO. Resoursedao;import jdbc. Jdbcutil;public class Resoursedaoimpl implements Resoursedao {private jdbcutil ju;public Resoursedaoimpl () {ju=new Jdbcutil ();} @Overridepublic Boolean insert (Resourse R) throws SQLException {String sql= "insert into Resourse values (0, '" +r.getword () + "', '"+R.getresourse_path ()+"'," +r.getisused () + "," +r.getqid () + "," "
+r.getuphone () + "')"; return Ju. Write (SQL);}}

6. Add a few sentences to the servlet written by the great God in step one

Package Servlet;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.net.urlencoder;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;import Bean. Resourse;import DAO. Resoursedao;import Daoimpl.resoursedaoimpl; @WebServlet ("/uploadservlet") public class Uploadservlet extends HttpServlet {/** * */private static final long serialversionuid = 1l;public void doget (HttpServletRequest request, Ht Tpservletresponse response) throws Servletexception, IOException { String value= ""; Resoursedao rd=new Resoursedaoimpl ();//new! Response.setcharacterencoding ("Utf-8"); Get the uploaded files to save the directory, the uploaded files are stored in the Web-inf directory, not allow direct access to the outside world, to ensure the security of the uploaded file String savepath = This.getservletcontext (). Getrealpat H"/teach/video");                File File = new file (Savepath); Determine if the saved directory for the uploaded file exists if (!file.exists () &&!file.isdirectory ()) {System.out.printl                    N (savepath+ "directory does not exist, need to create");                Create directory File.mkdir ();                }//message prompt String message = ""; try{//Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory Disk                    Fileitemfactory factory = new Diskfileitemfactory ();                     2. Create a file upload parser servletfileupload upload = new Servletfileupload (factory);                     Solve the upload file name of the Chinese garbled upload.setheaderencoding ("UTF-8"); 3, determine whether the data submitted is the upload form data if (!                    Servletfileupload.ismultipartcontent (Request)) {//Get data return in traditional way; }//4, using the Servletfileupload parser to parse the uploaded data, parse the result backis a list<fileitem> collection, and each fileitem corresponds to the entry of a form form list<fileitem> list = Upload.parserequest (re                    Quest);                             for (Fileitem item:list) {//If the data that is encapsulated in the fileitem is a normal input item if (Item.isformfield ()) {                            String name = Item.getfieldname ();                             Solve the problem of Chinese garbled data of ordinary input itemsvalue = item.getstring ("UTF-8");Value = new String (value.getbytes ("iso8859-1"), "UTF-8");                        SYSTEM.OUT.PRINTLN (name + "=" + value); }else{//If the Fileitem package is the upload file//Get uploaded file name,String filenamee=item.getname (); String filename = "http://localhost:8080/soga/teach/video/" +item.getname ();//new! Add to Database!!! filename=checkstring (filename);//new! SYSTEM.OUT.PRINTLN (filename);//new! Resourse r=new resourse (value,filename,0, "188*******");//This is the constructor in your own entity class System.out.println (R D.insert (R));//new!                            if (Filenamee==null | | Filenamee.trim (). Equals ("")) {continue; }//Note: Different browser submissions are not the same file name, some browsers submit the file name is with the path, such as: C:\a\b\1.txt, and some are only a single Pure file name, such as: 1.txt//processing gets to the path portion of the file name of the uploaded files, leaving only the file name part Filenamee = FILENAMEE.S                            Ubstring (filenamee.lastindexof ("\ \") +1);                            Gets the input stream of the uploaded file in item inputstream in = Item.getinputstream ();                            Create a file output stream FileOutputStream out = new FileOutputStream (savepath + "\ \" + Filenamee);                            Create a buffer of byte buffer[] = new byte[1024];                            Determines whether the data in the input stream has been read out of the identity int len = 0;              The loop reads the input stream into the buffer, (len=in.read (buffer)) >0 indicates that there is data while ((Len=in.read (buffer)) >0) {                  Writes the data of the buffer to the specified directory (savepath + "\ \" + filename) using the FileOutputStream output stream.                            Write (buffer, 0, Len);                            }//Close input stream in.close ();                            Turn off the output stream out.close ();                            Delete temporary files generated when processing file uploads item.delete (); message = "File Upload succeeded!"                        "; }}}catch (Exception e) {message= "File upload failed!                    ";                                    E.printstacktrace ();                } request.setattribute ("message", message);    Request.getrequestdispatcher ("/message.jsp"). Forward (request, response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex    ception {doget (request, response);    }Public  String checkstring (String str) {//new! String returnstr = ""; if (Str.indexof ("")! =-1) {//Determine if the string contains single quotes returnstr = str.replace ("'", "" "); str = RETURNSTR; } return str; }  }

  

The red is my newly added.?? No, but I commented after the new code://new!

Third, read the URL from the database, the content is displayed on the Web page.

This is about JSON. Complete steps See: JSONP cross-domain access servlet interface get JSON array, and render data, front and back end complete

H5 upload the video to the server, save to the specified location, save the URL to the database, and then display it in a specific format

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.