JavaWeb-SpringBoot(抖音)_二、服务器间通讯

 

  

  JavaWeb-SpringBoot(抖音)_一、抖音项目制作  传送门 

  JavaWeb-SpringBoot(抖音)_二、服务器间通讯  传送门

  JavaWeb-SpringBoot(抖音)_三、抖音项目后续  传送门

 

 

分析服务器

  无法通过腾讯云点播服务器得到提交作品封面信息,那么需要自己去做一个服务器去专门上传封面信息

  腾讯云点播服务器提供视频发布,自己做的服务器去上传封面信息

 

  自己搭建的SSH服务器上传视频封面

 

package com.Gary.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.Gary.domain.Lfile;
import com.Gary.service.FileService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    
    private FileService fileService;
    
    //查找所有的文件
    public String getData() throws Exception {
    
        List<Lfile> list =  fileService.findAllLfile();
        
        ActionContext.getContext().put("list", list);
        
        return "index";
    
    }
    
    
    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        //判断数据库中是否存在相同名字的文件
        boolean success =fileService.JudgeLfilename(uploadFileName);
        //如果有相同的filename我们就不进行插入
        if(success) {
            fileService.addFile(lfile);
        }
        
        
        return "default";
    }

    
    public FileService getFileService() {
        return fileService;
    }


    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

package com.Gary.service;

import java.util.List;

import com.Gary.dao.FileDao;
import com.Gary.domain.Lfile;

public class FileService {

    private FileDao fileDao;
    
    public FileDao getFileDao() {
        return fileDao;
    }

    public void setFileDao(FileDao fileDao) {
        this.fileDao = fileDao;
    }

    public void addFile(Lfile lfile) {
        fileDao.addFile(lfile);
        
    }

    public List<Lfile> findAllLfile() {
        
        return fileDao.findAllLfile();
    }

    //判断是否有相同同名的文件
    public boolean JudgeLfilename(String uploadFileName) {
        int num = fileDao.JudgeLfilename(uploadFileName);
        //如果num>0证明数据库中存在相同的文件名称
        if(num>0)
        {
            return false;
        }else {
            return true;
        }

    }

}
FileService.java

 

package com.Gary.dao;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.Gary.domain.Lfile;

public class FileDao extends HibernateDaoSupport{

    public void addFile(Lfile lfile) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.save(lfile);
    }

    public List<Lfile> findAllLfile() {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select * from lfile";
        NativeQuery query = session.createSQLQuery(sql);
        query.addEntity(Lfile.class);
        List<Lfile> list = query.list();
        
        return list;
    }

    public int JudgeLfilename(String uploadFileName) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select count(*) from lfile where filename = ?";
        NativeQuery query = session.createSQLQuery(sql);
        query.setParameter(1, uploadFileName);
        BigInteger result = (BigInteger) query.uniqueResult();
        
        return result.intValue();
    }


}
FileDao.java

 

 

 

搭建SSH项目Fileio并测试

  Fileio程序结构

  

  测试index.jsp页面显示出文字Gary index.jsp,编写FileAction_addFile请求显示出文字"成功"

public class FileAction extends ActionSupport{

    public String addFile() throws Exception {
        
        System.out.println("成功!");
        
        return "success";
    }

}

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
Gary index.jsp
</body>
</html>
index.jsp

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>成功!!</h1>

</body>
</html>
success.jsp

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Fileio</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  
  <!-- 扩大session的范围    扩大到视图加载完毕-->
  <filter>
      <filter-name>openSession</filter-name>
      <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
  </filter>
  <filter-mapping>
      <filter-name>openSession</filter-name>
      <url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 让struts启动 -->
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
</web-app>
web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 链接数据库 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql:///uploadio"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 与数据库会话-->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    
        <property name="mappingDirectoryLocations" value="classpath:com/Gary/domain"></property>
    </bean>
    
    <!-- 事务 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!-- 通知 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 织入 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.Gary.service.*.*(..))" id="pc"/>
        <aop:advisor advice-ref="advice" pointcut-ref="pc"/>
    </aop:config>
    
    <!-- 配制action -->
        <!-- 配置action -->
    <bean name="fileAction" class="com.Gary.web.FileAction" scope="prototype">
        
    </bean>
    
    
    
    
</beans>
applicationContext.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
    
<struts>

    <!-- 开启动态方法的调用 -->
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <!-- 让spring帮我们创建action -->
    <package name="Fileio" namespace="/" extends="struts-default">
        <!-- 允许所有的方法 -->    
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <!-- 配置action TODO -->
        
        <action name="FileAction_*" class="com.Gary.web.FileAction" method="{1}" >
            
            <result name="success">/success.jsp</result>
        </action>
        
    </package>


</struts>
struts.xml

 

 

书写indedx页面

   存储图片信息五个字段ID、文件名称、文件类型、url、创建时间

<table class="table">
            <thead>
                <tr>
                    <th>id</th>
                    <th>预览</th>
                    <th>文件名称</th>
                    <th>文件类型</th>
                    <th>url</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            
            <tbody>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                    <td>5</td>
                    <td>6</td>
                </tr>
            </tbody>
            
        </table>

 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gary文件上传</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
    <h2 style="margin-left: 100px">Gary文件上传服务器</h2>
    <div class="container">
        <table class="table">
            <thead>
                <tr>
                    <th>id</th>
                    <th>预览</th>
                    <th>文件名称</th>
                    <th>文件类型</th>
                    <th>url</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            
            <tbody>
                <tr>
                    <td>1</td>
                    <td>2</td>
                    <td>3</td>
                    <td>4</td>
                    <td>5</td>
                    <td>6</td>
                </tr>
            </tbody>
            
        </table>
    </div>
</body>
</html>
index.html

 

 

书写Upload页面

    <!-- enctype="multipart/form-data" 文件数据以二进制流传递到action -->
    <form action="${pageContext.request.contextPath}/FileAction_addFile " method="post" enctype="multipart/form-data">
        上传文件:
        <input type="file" name="upload">
        <br>
        <input type="submit" value="提交">
    </form>

 

  

  测试当点击提交按钮后,发送addFile()请求,文件跳转到index.jsp

public class FileAction extends ActionSupport{

    public String addFile() throws Exception {
        
        System.out.println("成功!");
        
        return "index";
    }

}

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gary文件上传</title>
</head>
<body>

<h2>Gary文件上传</h2>

    <!-- enctype="multipart/form-data" 文件数据以二进制流传递到action -->
    <form action="${pageContext.request.contextPath}/FileAction_addFile " method="post" enctype="multipart/form-data">
        上传文件:
        <input type="file" name="upload">
        <br>
        <input type="submit" value="提交">
    </form>

</body>
</html>
upload.jsp

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
    
<struts>

    <!-- 开启动态方法的调用 -->
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <!-- 让spring帮我们创建action -->
    <constant name="struts.objectFactory" value="spring"></constant>


    <!-- 让spring帮我们创建action -->
    <package name="Fileio" namespace="/" extends="struts-default">
        <!-- 允许所有的方法 -->    
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <!-- 配置action TODO -->
        
        <action name="FileAction_*" class="com.Gary.web.FileAction" method="{1}" >
            <result name="index">/index.jsp</result>
            
        </action>
        
    </package>


</struts>
struts.xml

 

package com.Gary.web;

import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    public String addFile() throws Exception {
        
        System.out.println("成功!");
        
        return "index";
    }

}
FileAction.java

 

 

实现上传文件

  配置struts拦截器,实现上传图片功能

            <interceptor-ref name="fileUpload">
                <!-- 允许文件类型 -->
                <param name="allowedType">image/bmp,image/x-png,image/gif,image/jpeg</param>
                <!-- 允许文件最大的大小 -->
                <param name="maximumSize">5M</param>
            </interceptor-ref>
             <!-- 使用默认的栈 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>

 

  在FileAction中添加文件的属性上传的文件upload、文件的类型uploadContentType、文件的名称uploadFileName

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;

 

  在addFile()请求中输出上传文件的信息

    public String addFile() throws Exception {
        
        System.out.println(upload);
        System.out.println(uploadContentType);
        System.out.println(uploadFileName);
        
        return "index";
    }

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gary文件上传</title>
</head>
<body>

<h2>Gary文件上传</h2>

    <!-- enctype="multipart/form-data" 文件数据以二进制流传递到action -->
    <form action="${pageContext.request.contextPath}/FileAction_addFile " method="post" enctype="multipart/form-data">
        上传文件:
        <input type="file" name="upload">
        <br>
        <input type="submit" value="提交">
    </form>

</body>
</html>
upload.jsp

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
    "http://struts.apache.org/dtds/struts-2.5.dtd">
    
<struts>

    <!-- 开启动态方法的调用 -->
    <constant name="struts.devMode" value="true" />
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />

    <!-- 让spring帮我们创建action -->
    <constant name="struts.objectFactory" value="spring"></constant>


    <!-- 让spring帮我们创建action -->
    <package name="Fileio" namespace="/" extends="struts-default">
        <!-- 允许所有的方法 -->    
        <global-allowed-methods>regex:.*</global-allowed-methods>
        <!-- 配置action TODO -->
        
        <action name="FileAction_*" class="com.Gary.web.FileAction" method="{1}" >
            <result name="index">/index.jsp</result>
            <interceptor-ref name="fileUpload">
                <!-- 允许文件类型 -->
                <param name="allowedType">image/bmp,image/x-png,image/gif,image/jpeg</param>
                <!-- 允许文件最大的大小 -->
                <param name="maximumSize">5M</param>
            </interceptor-ref>
        <!-- 使用默认的栈 -->
            <interceptor-ref name="defaultStack"></interceptor-ref>
            
        </action>
        
    </package>


</struts>
struts.xml

 

package com.Gary.web;

import java.io.File;

import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    

    public String addFile() throws Exception {
        
        System.out.println(upload);
        System.out.println(uploadContentType);
        System.out.println(uploadFileName);
        
        return "index";
    }

    
    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

 

完成文件的上传

  我们从本地获得图片资源后,在服务器下没有该路径,那么就在其中创建一个空的File文件,将获得的的图片以二进制流保存到服务器的File中

 

   将视频页面上传至服务器逻辑

        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));

 

 

package com.Gary.web;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    

    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        return "index";
    }

    
    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

 

书写rom元数据

  创建存储文件实体

    private String id;
    private String filename;
    private String filetype;
    private String url;
    private String createtime;

 

  通过Lfile.hbm.xml自动生成数据库表单

    <hibernate-mapping package="com.Gary.domain">
       <class name="Lfile" table="lfile">
           <id name="id">
               <generator class="uuid"></generator>
           </id>
           <property name="filename" column="filename"></property>
           <property name="filetype" column="filetype"></property>
           <property name="url" column="url"></property>
           <property name="createtime" column="createtime"></property>
       </class>

 

 

package com.Gary.domain;

public class Lfile {

    private String id;
    private String filename;
    private String filetype;
    private String url;
    private String createtime;
    
    
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getFilename() {
        return filename;
    }
    public void setFilename(String filename) {
        this.filename = filename;
    }
    public String getFiletype() {
        return filetype;
    }
    public void setFiletype(String filetype) {
        this.filetype = filetype;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getCreatetime() {
        return createtime;
    }
    public void setCreatetime(String createtime) {
        this.createtime = createtime;
    }
    
    
}
Lfile.java

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
    <hibernate-mapping package="com.Gary.domain">
       <class name="Lfile" table="lfile">
           <id name="id">
               <generator class="uuid"></generator>
           </id>
           <property name="filename" column="filename"></property>
           <property name="filetype" column="filetype"></property>
           <property name="url" column="url"></property>
           <property name="createtime" column="createtime"></property>
       </class>
   
   
   </hibernate-mapping>
Lfile.hbm.xml

 

 

书写Web层完成添加文件

  web层接收到文件通过service层传输文件到Dao层保存文件到数据库逻辑

 

   配置applicationContext.xml事务

    <!-- 配制action -->
        <!-- 配置action -->
    <bean name="fileAction" class="com.Gary.web.FileAction" scope="prototype">
        <property name="fileService" ref="fileService"></property>
    </bean>
    
    <!-- 配置service -->
    <bean name="fileService" class="com.Gary.service.FileService">
        <property name="fileDao" ref="fileDao"></property>
    </bean>
    
    <!-- 配置dao -->
    <bean name="fileDao" class="com.Gary.dao.FileDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

 

 

   Web层

package com.Gary.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.Gary.domain.Lfile;
import com.Gary.service.FileService;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    
    private FileService fileService;
    
    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        fileService.addFile(lfile);
        
        return "index";
    }

    
    public FileService getFileService() {
        return fileService;
    }


    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

  Service层

package com.Gary.service;

import com.Gary.dao.FileDao;
import com.Gary.domain.Lfile;

public class FileService {

    private FileDao fileDao;
    
    public FileDao getFileDao() {
        return fileDao;
    }

    public void setFileDao(FileDao fileDao) {
        this.fileDao = fileDao;
    }

    public void addFile(Lfile lfile) {
        fileDao.addFile(lfile);
        
    }

}
FileService.java

 

  Dao层

package com.Gary.dao;

import org.hibernate.Session;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.Gary.domain.Lfile;

public class FileDao extends HibernateDaoSupport{

    public void addFile(Lfile lfile) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.save(lfile);
    }

}
FileDao.java

 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 链接数据库 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql:///uploadio"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 与数据库会话-->
    <bean name="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
    
        <property name="mappingDirectoryLocations" value="classpath:com/Gary/domain"></property>
    </bean>
    
    <!-- 事务 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
    <!-- 通知 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    
    <!-- 织入 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.Gary.service.*.*(..))" id="pc"/>
        <aop:advisor advice-ref="advice" pointcut-ref="pc"/>
    </aop:config>
    
    <!-- 配制action -->
        <!-- 配置action -->
    <bean name="fileAction" class="com.Gary.web.FileAction" scope="prototype">
        <property name="fileService" ref="fileService"></property>
    </bean>
    
    <!-- 配置service -->
    <bean name="fileService" class="com.Gary.service.FileService">
        <property name="fileDao" ref="fileDao"></property>
    </bean>
    
    <!-- 配置dao -->
    <bean name="fileDao" class="com.Gary.dao.FileDao">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    
</beans>
applicationContext.xml

 

 

查询所有的file

  通过Web层的getData()请求查询所有的file文件

  index.jsp页面作为文件的显示

<table class="table">
            <thead>
                <tr>
                    <th>id</th>
                    <th>预览</th>
                    <th>文件名称</th>
                    <th>文件类型</th>
                    <th>url</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            
            <tbody>
                <s:iterator value="list" var="lfile">
                <tr>
                    <td><s:property value="#lfile.id"/> </td>
                    <td><img style="height: 54px;width: 96px" src="${pageContext.request.contextPath }/images/<s:property value="#lfile.filename"/>"> </td>
                    <td><s:property value="#lfile.filename"/></td>
                    <td><s:property value="#lfile.filetype"/></td>
                    <td><s:property value="#lfile.url"/></td>
                    <td><s:property value="#lfile.createtime"/></td>
                </tr>
                </s:iterator>
            </tbody>
            
        </table>

 

   Web层查找所有的文件

    //查找所有的文件
    public String getData() throws Exception {
    
        List<Lfile> list =  fileService.findAllLfile();
        
        ActionContext.getContext().put("list", list);
        
        return "index";
    
    }

 

   Dao层查找数据库中所有的文件

    public List<Lfile> findAllLfile() {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select * from lfile";
        NativeQuery query = session.createSQLQuery(sql);
        query.addEntity(Lfile.class);
        List<Lfile> list = query.list();
        
        return list;
    }

 

 

 

package com.Gary.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.Gary.domain.Lfile;
import com.Gary.service.FileService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    
    private FileService fileService;
    
    //查找所有的文件
    public String getData() throws Exception {
    
        List<Lfile> list =  fileService.findAllLfile();
        
        ActionContext.getContext().put("list", list);
        
        return "index";
    
    }
    
    
    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        fileService.addFile(lfile);
        
        return "index";
    }

    
    public FileService getFileService() {
        return fileService;
    }


    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

package com.Gary.service;

import java.util.List;

import com.Gary.dao.FileDao;
import com.Gary.domain.Lfile;

public class FileService {

    private FileDao fileDao;
    
    public FileDao getFileDao() {
        return fileDao;
    }

    public void setFileDao(FileDao fileDao) {
        this.fileDao = fileDao;
    }

    public void addFile(Lfile lfile) {
        fileDao.addFile(lfile);
        
    }

    public List<Lfile> findAllLfile() {
        
        return fileDao.findAllLfile();
    }

}
FileService.java

 

package com.Gary.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.Gary.domain.Lfile;

public class FileDao extends HibernateDaoSupport{

    public void addFile(Lfile lfile) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.save(lfile);
    }

    public List<Lfile> findAllLfile() {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select * from lfile";
        NativeQuery query = session.createSQLQuery(sql);
        query.addEntity(Lfile.class);
        List<Lfile> list = query.list();
        
        return list;
    }

}
FileDao.java

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gary文件上传</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body>
    <h2 style="margin-left: 100px">Gary文件上传服务器</h2>
    <div class="container">
        <table class="table">
            <thead>
                <tr>
                    <th>id</th>
                    <th>预览</th>
                    <th>文件名称</th>
                    <th>文件类型</th>
                    <th>url</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            
            <tbody>
                <s:iterator value="list" var="lfile">
                <tr>
                    <td><s:property value="#lfile.id"/> </td>
                    <td><img style="height: 54px;width: 96px" src="${pageContext.request.contextPath }/images/<s:property value="#lfile.filename"/>"> </td>
                    <td><s:property value="#lfile.filename"/></td>
                    <td><s:property value="#lfile.filetype"/></td>
                    <td><s:property value="#lfile.url"/></td>
                    <td><s:property value="#lfile.createtime"/></td>
                </tr>
                </s:iterator>
            </tbody>
            
        </table>
    </div>
</body>
</html>
index.jsp

 

 

解决文件服务器Bug--上传相同重复的文件

  Web层对提交相同文件进行处理

    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        //判断数据库中是否存在相同名字的文件
        boolean success =fileService.JudgeLfilename(uploadFileName);
        //如果有相同的filename我们就不进行插入
        if(success) {
            fileService.addFile(lfile);
        }
        
        
        return "default";
    }

 

  Service层逻辑:判断数据库中是否有重复的数据,如果数量大于1那么则不能再往服务器中添加数据,反之可添加数据

    public boolean JudgeLfilename(String uploadFileName) {
        int num = fileDao.JudgeLfilename(uploadFileName);
        //如果num>0证明数据库中存在相同的文件名称
        if(num>0)
        {
            return false;
        }else {
            return true;
        }

    }

 

  Dao层对数据库的查询处理

    public int JudgeLfilename(String uploadFileName) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select count(*) from lfile where filename = ?";
        NativeQuery query = session.createSQLQuery(sql);
        query.setParameter(1, uploadFileName);
        BigInteger result = (BigInteger) query.uniqueResult();
        
        return result.intValue();
    }

 

 

package com.Gary.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.Gary.domain.Lfile;
import com.Gary.service.FileService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    
    private FileService fileService;
    
    //查找所有的文件
    public String getData() throws Exception {
    
        List<Lfile> list =  fileService.findAllLfile();
        
        ActionContext.getContext().put("list", list);
        
        return "index";
    
    }
    
    
    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        //判断数据库中是否存在相同名字的文件
        boolean success =fileService.JudgeLfilename(uploadFileName);
        //如果有相同的filename我们就不进行插入
        if(success) {
            fileService.addFile(lfile);
        }
        
        
        return "default";
    }

    
    public FileService getFileService() {
        return fileService;
    }


    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }


}
FileAction.java

 

package com.Gary.service;

import java.util.List;

import com.Gary.dao.FileDao;
import com.Gary.domain.Lfile;

public class FileService {

    private FileDao fileDao;
    
    public FileDao getFileDao() {
        return fileDao;
    }

    public void setFileDao(FileDao fileDao) {
        this.fileDao = fileDao;
    }

    public void addFile(Lfile lfile) {
        fileDao.addFile(lfile);
        
    }

    public List<Lfile> findAllLfile() {
        
        return fileDao.findAllLfile();
    }

    //判断是否有相同同名的文件
    public boolean JudgeLfilename(String uploadFileName) {
        int num = fileDao.JudgeLfilename(uploadFileName);
        //如果num>0证明数据库中存在相同的文件名称
        if(num>0)
        {
            return false;
        }else {
            return true;
        }

    }

}
FileService.java

 

package com.Gary.dao;

import java.math.BigInteger;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.query.NativeQuery;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import com.Gary.domain.Lfile;

public class FileDao extends HibernateDaoSupport{

    public void addFile(Lfile lfile) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.save(lfile);
    }

    public List<Lfile> findAllLfile() {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select * from lfile";
        NativeQuery query = session.createSQLQuery(sql);
        query.addEntity(Lfile.class);
        List<Lfile> list = query.list();
        
        return list;
    }

    public int JudgeLfilename(String uploadFileName) {
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        String sql = "select count(*) from lfile where filename = ?";
        NativeQuery query = session.createSQLQuery(sql);
        query.setParameter(1, uploadFileName);
        BigInteger result = (BigInteger) query.uniqueResult();
        
        return result.intValue();
    }


}
FileDao.java

 

 

跨两个服务器请求

  一个是8080端口shakes项目,一个是8081端口Fileio项目

  不带数据的跨域请求

<a href="http://localhost:8081/Fileio/FileAction_test">这里</a>

 

    //实现跨域请求  是否可以调用这个函数
    public String test() throws Exception
    {
        System.out.println("跨域请求!!");
        System.out.println(test);
        return "index";
    }

 

  带数据的跨域请求

<form action="http://localhost:8081/Fileio/FileAction_test" method="post">
            <input type="text" name="test">
            <input type="submit">
        </form>

 

    //实现跨域请求  是否可以调用这个函数
    public String test() throws Exception
    {
        System.out.println("跨域请求!!");
        System.out.println(test);
        return "index";
    }

 

  上传文件的ajax跨域请求

        <form id="formtest" action="http://localhost:8081/Fileio/FileAction_fileTest" method="post" enctype="multipart/form-data">
            <input type="file" name="upload">
            <input type="submit">
        </form>

 

public String fileTestAjax() throws Exception{
        
        System.out.println(upload);
        System.out.println(uploadContentType);
        System.out.println(uploadFileName);
        
        ServletActionContext.getResponse().getWriter().write("{\"success\":"+true+"}");
        return null;
    }

 

  点击发送图片后发送ajax文件请求

function uploadVideoAndCover()
            {
                
                //$.post(
                //action的地址
                //"http://127.0.0.1:8081/Fileio/FileAction_ajax",
                //提交的数据
                //{"test":"Gary"},
                //回调函数
                //function(data)
                //{
                //    
                //},
                //数据格式
                //"json"
                //)
                
                //表单数 据
                var formData = new FormData($("#formtest")[0]);
                
                $.ajax({
                    type:"POST",
                    url:"http://127.0.0.1:8081/Fileio/FileAction_fileTestAjax",
                    async:false,
                    cache:false,
                    //传入的数据
                    data:formData,
                    //是否处理数据
                    processData:false,
                    //内容类型
                    contentType:false,
                    dataType:"json",
                    success:function(data)
                    {
                        
                    },
                    error:function(data)
                    {
                        
                    }
                })
                
                
                //upload();    
            }

 

 

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script async="" src="register-add-music_files/analytics.js"></script>
<script src="register-add-music_files/slardar.js"></script>
<script>
    window.Slardar && window.Slardar.install({
        sampleRate : 1,
        bid : 'douyin_web',
        pid : 'musician_apply_submit',
        ignoreAjax : [],
        ignoreStatic : []
    });
</script>
<title>&nbsp;抖音音乐人</title>
<meta charset="utf-8">
<meta http-equiv="”Cache-Control”" content="”no-transform”">
<meta http-equiv="”Cache-Control”" content="”no-siteapp”">
<meta name="baidu-site-verification" content="szjdG38sKy">
<meta name="keywords" content="抖音看见音乐,看见音乐计划,抖音音乐人,原创音乐,看见音乐计划官网">
<meta name="description" content="抖音看见音乐计划,你的音乐,我看得见">
<link rel="shortcut icon" href="https://s3.bytecdn.cn/aweme/resource/web/static/image/logo/favicon_v2_7145ff0.ico" type="image/x-icon">
<meta http-equiv="X-UA-Compatible" content="IE=Edge;chrome=1">
<link rel="dns-prefetch" href="https://s3.bytecdn.cn/">
<link rel="dns-prefetch" href="https://s3a.bytecdn.cn/">
<link rel="dns-prefetch" href="https://s3b.bytecdn.cn/">
<link rel="dns-prefetch" href="https://s0.pstatp.com/">
<link rel="dns-prefetch" href="https://s1.pstatp.com/">
<link rel="dns-prefetch" href="https://s2.pstatp.com/">
<link rel="stylesheet" href="register-add-music_files/base_4a834a9.css">
<link rel="stylesheet" href="register-add-music_files/base_ce73669.css">
<link rel="stylesheet" href="register-add-music_files/dropkick_1b1894b.css">
<!--[if IE]><script src="//s3a.bytecdn.cn/aweme/resource/web/static/script/lib/fix-ie8_e8a0650.js"></script><![endif]-->
<script src="register-add-music_files/core_1f49c51.js"></script>
<script src="register-add-music_files/jquery.js"></script>
<script src="register-add-music_files/raven_8c2f9e8.js"></script>
<script>
    window.PAGEVIEW_NAME = '/musician_apply_submit/';
</script>
<script>
    // BA全局变量
    var baAccount = window.AME_BA_ID || 'fe557d1f75199e';
    var baevent = function() {
    };

    (function() {
        var sampleRate = 100; // 采样比例,即上报量占总流量的百分比

        !function(t, e, a, n, s, c) {
            t.ToutiaoAnalyticsObject = s, t[s] = t[s] || function() {
                (t[s].q = t[s].q || []).push(arguments)
            }, t[s].t = 1 * new Date, t[s].s = c;
            var i = e.createElement(a);
            i.async = 1, i.src = n, e.getElementsByTagName("head")[0]
                    .appendChild(i)
        }(window, document, "script",
                "//s3.bytecdn.cn/ta/resource/v0/analytics.js", "ba");

        ba('create', baAccount, {
            'sampleRate' : sampleRate
        });
        ba('send', 'pageview');

        baevent = function(category, action, label, value) {
            console.log("ba:" + category + "," + action + "," + label);
            if (category != 'event') {
                ba('send', 'event', category, action, label,
                        typeof value !== 'undefined' ? value : 1);
            }
        };
    })();
</script>
<script async="" src="register-add-music_files/analytics_002.js"></script>
<script>
    var gaAccount = window.AME_GA_ID || 'UA-75850242-4';

    var _gaq = _gaq || [];
    var gaqpush = function() {
    };
    var gaevent = function() {
    };
    var gapageview = function() {
    };
    var trackPV = gapageview;

    var sampleRate = 20;

    function initGA() {

        if (sampleRate && gaAccount) {
            window.onerror = function(message, file, line) {
                var msg = message, f = file, l = line;
                if (typeof message === 'object') {
                    msg = message.message;
                    f = message.fileName;
                    l = message.lineNumber;
                }
                var sFormattedMessage = '[' + f + ' (' + l + ')]' + msg;
                window.gaevent ? gaevent('Exceptions', sFormattedMessage,
                        location.pathname + '::::' + navigator.userAgent) : '';
            };

            var test_channel = "", test_version = "", utm_source = "";

            // var ua = navigator.userAgent;

            (function(i, s, o, g, r, a, m) {
                i['GoogleAnalyticsObject'] = r;
                i[r] = i[r] || function() {
                    (i[r].q = i[r].q || []).push(arguments)
                }, i[r].l = 1 * new Date();
                a = s.createElement(o), m = s.getElementsByTagName(o)[0];
                a.async = 1;
                a.src = g;
                m.parentNode.insertBefore(a, m)
            })(window, document, 'script',
                    '//www.google-analytics.com/analytics.js', 'ga');

            // Replace with your property ID.
            ga('create', gaAccount, {
                'sampleRate' : sampleRate
            });

            //Init GA Function
            gapageview = function(pageName) {
                ga('send', 'pageview', pageName);
                console.log('ga:pageview', pageName);
            };

            gaqpush = function(ga_event, ga_label) {
                gaevent('event', ga_event, ga_label);
            };

            gaevent = function(category, action, label, value) {
                if (test_channel.indexOf(action) > -1)
                    label = label + test_version;
                console.log("ga:" + category + "," + action + "," + label);
                if (category != 'event') {
                    ga('send', 'event', category, action, label,
                            typeof value !== "undefined" ? value : 1);
                }
                if (typeof window.baevent == "function") {
                    baevent(category, action, label, value);
                }
            };

            gapageview(window.PAGEVIEW_NAME);

            $("html")
                    .on(
                            'click',
                            '[ga_event]',
                            function(e) {
                                var $this = $(this);
                                var ga_category = $this.attr('ga_category')
                                        || 'event';
                                var ga_event = $this.attr('ga_event');
                                var ga_label = $this.attr('ga_label');
                                gaevent(ga_category, ga_event, ga_label);
                                if ($this.is('a')) {
                                    var href = $this.attr('href') || '', target = this.target;
                                    if (!(href[0] === '#'
                                            || target === "_blank" || e
                                            .isDefaultPrevented())) {
                                        setTimeout(function() {
                                            location.href = href
                                        }, 400);
                                        return false
                                    }
                                }
                            });
        }
    }

    initGA();
</script>
<link rel="stylesheet" href="register-add-music_files/index_db26f14.css">
</head>
<body>
    <div class="main-content-block">

        <div th:replace="~{fragments/header::header}"></div>

        <div class="common-header">
            <div class="common-module-container">
                <div class="common-module">
                    <img src="register-add-music_files/icon_1_active_cc77279.png">
                    <p class="common-module-txt">
                        填写资料
                        <span id="verifyStatus" class="verify-status" style="display: inline;">(审核中)</span>
                    </p>
                </div>
                <div class="common-hr"></div>
                <div class="common-module">
                    <img src="register-add-music_files/icon_2_active_5b30557.png">
                    <p class="common-module-txt">提交作品</p>
                </div>
                <div class="common-hr"></div>
                <div class="common-module">
                    <img src="register-add-music_files/icon_3_grey_b8ff386.png">
                    <p class="common-module-txt">等待审核</p>
                </div>
            </div>
        </div>
        <div class="zz-toast" id="zz-toast">
            <h4 id="zz-toast-title">错误提示</h4>
            <p id="zz-toast-txt" class="zz-toast-txt">This is a danger message.</p>
        </div>
        <div class="container">
            <p class="step-tips">
                <span>声明:抖音团队不会以任何形式向您收取推广费用,如您遇到收费情况,请发邮件至举报邮箱:</span>
                <a href="mailto:musician@bytedance.com" class="step-tips-email">musician@bytedance.com</a>
            </p>
            <p class="step-title">提交作品</p>
            <p class="submit-step-tips-musi">
                建议整曲和剪辑版本(如副歌部分)一起提交,30s-60s的剪辑版本更适合抖音拍摄和传播哦
                <br>
                歌曲的剪辑版本建议命名为歌名-剪辑版,更方便被推荐~
            </p>
            <div class="step-form-submit">
                <div class="submit-step-upload" id="showModalBtn">+ 添加音乐</div>
                <div class="submit-tab-group">
                    <button id="showMusic" class="submit-tab-btn" style="color: #4a4a4a">已提交&nbsp;</button>
                    <span class="submit-tab-btn">|</span>
                    <button id="showAdded" class="submit-tab-btn" style="color: #ccc" disabled="disabled">&nbsp;新增项</button>
                </div>
                <div class="submit-music-container">
                    <div class="submit-music-header">
                        <div class="submit-music-cover">封面</div>
                        <div class="submit-music-name">音乐</div>
                        <div class="submit-music-audio">试听</div>
                        <div class="submit-music-campus">是否高校好声音</div>
                    </div>
                    <div id="musicListCont" class="submit-music-list">暂无作品,点击添加音乐添加你的作品~</div>
                </div>
                <div class="submit-music-pages" id="pages">
                    <button id="pagePre" class="submit-music-page-btn" disabled="disabled" style="color: #ccc">&lt;上一页</button>
                    <span>/</span>
                    <button id="pageNxt" class="submit-music-page-btn" disabled="disabled" style="color: #ccc">下一页 &gt;</button>
                </div>
                <div class="submit-step-button-group">
                    <div class="step-button" id="submitApply">提交</div>
                </div>
                <div class="submit-modal" id="modal">
                    <div class="submit-modal-container" id="modalContainer">
                        <p class="step-title">添加音乐</p>
                        <form class="submit-modal-form" id="uploadMusicForm" novalidate="novalidate">
                            <div class="submit-modal-group">
                                <label class="submit-modal-label label-not-null">风格</label>
                                <div class="dk-select step-select" id="dk0-stepSelect" style="margin-left: -200px">

                                    <ul class="dk-select-options" id="dk0-listbox" role="listbox" aria-expanded="false">
                                        <li class="dk-optgroup">
                                            <div class="dk-optgroup-label">中文</div>
                                            <ul class="dk-optgroup-options">
                                                <li class="dk-option  dk-option-selected" data-value="[41,49]" text="流行" role="option" aria-selected="true" id="dk0-[41,49]">流行</li>
                                                <li class="dk-option " data-value="[41,50]" text="说唱" role="option" aria-selected="false" id="dk0-[41,50]">说唱</li>
                                                <li class="dk-option " data-value="[41,51]" text="电音" role="option" aria-selected="false" id="dk0-[41,51]">电音</li>
                                                <li class="dk-option " data-value="[41,53]" text="民谣" role="option" aria-selected="false" id="dk0-[41,53]">民谣</li>
                                                <li class="dk-option " data-value="[41,56]" text="动漫" role="option" aria-selected="false" id="dk0-[41,56]">动漫</li>
                                                <li class="dk-option " data-value="[41,54]" text="古风" role="option" aria-selected="false" id="dk0-[41,54]">古风</li>
                                                <li class="dk-option " data-value="[41,55]" text="摇滚" role="option" aria-selected="false" id="dk0-[41,55]">摇滚</li>
                                                <li class="dk-option " data-value="[41,93]" text="disco" role="option" aria-selected="false" id="dk0-[41,93]">disco</li>
                                            </ul>
                                        </li>
                                        <li class="dk-optgroup">
                                            <div class="dk-optgroup-label">欧美</div>
                                            <ul class="dk-optgroup-options">
                                                <li class="dk-option " data-value="[42,57]" text="流行" role="option" aria-selected="false" id="dk0-[42,57]">流行</li>
                                                <li class="dk-option " data-value="[42,58]" text="说唱" role="option" aria-selected="false" id="dk0-[42,58]">说唱</li>
                                                <li class="dk-option " data-value="[42,59]" text="电音" role="option" aria-selected="false" id="dk0-[42,59]">电音</li>
                                                <li class="dk-option " data-value="[42,61]" text="爵士" role="option" aria-selected="false" id="dk0-[42,61]">爵士</li>
                                                <li class="dk-option " data-value="[42,62]" text="乡村" role="option" aria-selected="false" id="dk0-[42,62]">乡村</li>
                                                <li class="dk-option " data-value="[42,63]" text="布鲁斯" role="option" aria-selected="false" id="dk0-[42,63]">布鲁斯</li>
                                                <li class="dk-option " data-value="[42,64]" text="民谣" role="option" aria-selected="false" id="dk0-[42,64]">民谣</li>
                                                <li class="dk-option " data-value="[42,92]" text="hiphop" role="option" aria-selected="false" id="dk0-[42,92]">hiphop</li>
                                                <li class="dk-option " data-value="[42,95]" text="disco" role="option" aria-selected="false" id="dk0-[42,95]">disco</li>
                                            </ul>
                                        </li>
                                        <li class="dk-optgroup">
                                            <div class="dk-optgroup-label">日韩</div>
                                            <ul class="dk-optgroup-options">
                                                <li class="dk-option " data-value="[43,67]" text="说唱" role="option" aria-selected="false" id="dk0-[43,67]">说唱</li>
                                                <li class="dk-option " data-value="[43,68]" text="电音" role="option" aria-selected="false" id="dk0-[43,68]">电音</li>
                                                <li class="dk-option " data-value="[43,85]" text="摇滚" role="option" aria-selected="false" id="dk0-[43,85]">摇滚</li>
                                                <li class="dk-option " data-value="[43,69]" text="动漫" role="option" aria-selected="false" id="dk0-[43,69]">动漫</li>
                                                <li class="dk-option " data-value="[43,65]" text="j-pop" role="option" aria-selected="false" id="dk0-[43,65]">j-pop</li>
                                                <li class="dk-option " data-value="[43,66]" text="k-pop" role="option" aria-selected="false" id="dk0-[43,66]">k-pop</li>
                                            </ul>
                                        </li>
                                        <li class="dk-optgroup">
                                            <div class="dk-optgroup-label">趣味</div>
                                            <ul class="dk-optgroup-options">
                                                <li class="dk-option " data-value="[44,70]" text="萌宠" role="option" aria-selected="false" id="dk0-[44,70]">萌宠</li>
                                                <li class="dk-option " data-value="[44,88]" text="儿童" role="option" aria-selected="false" id="dk0-[44,88]">儿童</li>
                                                <li class="dk-option " data-value="[44,71]" text="段子" role="option" aria-selected="false" id="dk0-[44,71]">段子</li>
                                                <li class="dk-option " data-value="[44,87]" text="可爱" role="option" aria-selected="false" id="dk0-[44,87]">可爱</li>
                                                <li class="dk-option " data-value="[44,90]" text="幽默" role="option" aria-selected="false" id="dk0-[44,90]">幽默</li>
                                            </ul>
                                        </li>
                                    </ul>
                                </div>
                                <select class="step-select" id="stepSelect" name="style" data-dkcacheid="0">
                                    <optgroup label="中文">
                                        <option value="[41,49]" selected="selected">流行</option>
                                        <option value="[41,50]">说唱</option>
                                        <option value="[41,51]">电音</option>
                                        <option value="[41,53]">民谣</option>
                                        <option value="[41,56]">动漫</option>
                                        <option value="[41,54]">古风</option>
                                        <option value="[41,55]">摇滚</option>
                                        <option value="[41,93]">disco</option>
                                    </optgroup>
                                    <optgroup label="欧美">
                                        <option value="[42,57]">流行</option>
                                        <option value="[42,58]">说唱</option>
                                        <option value="[42,59]">电音</option>
                                        <option value="[42,61]">爵士</option>
                                        <option value="[42,62]">乡村</option>
                                        <option value="[42,63]">布鲁斯</option>
                                        <option value="[42,64]">民谣</option>
                                        <option value="[42,92]">hiphop</option>
                                        <option value="[42,95]">disco</option>
                                    </optgroup>
                                    <optgroup label="日韩">
                                        <option value="[43,67]">说唱</option>
                                        <option value="[43,68]">电音</option>
                                        <option value="[43,85]">摇滚</option>
                                        <option value="[43,69]">动漫</option>
                                        <option value="[43,65]">j-pop</option>
                                        <option value="[43,66]">k-pop</option>
                                    </optgroup>
                                    <optgroup label="趣味">
                                        <option value="[44,70]">萌宠</option>
                                        <option value="[44,88]">儿童</option>
                                        <option value="[44,71]">段子</option>
                                        <option value="[44,87]">可爱</option>
                                        <option value="[44,90]">幽默</option>
                                    </optgroup>
                                </select>
                            </div>
                            <div class="submit-modal-group">
                                <label for="music" class="submit-modal-label label-not-null">歌曲名</label>
                                <input class="submit-modal-input" name="title" type="text">
                            </div>
                            <div class="submit-modal-group submit-modal-group--tips">
                                <label for="music" class="submit-modal-label label-not-null">封面文件</label>
                                <div type="text" class="submit-modal-file">
                                    <div class="submit-modal-button">上传封面文件</div>


                                
                                    <!-- 封面文件 -->
                                    <input id="cover-file-name" class="submit-modal-name" disabled="disabled" name="coverName">
                                    <input onchange="addCover(this)" name="file"  class="submit-modal-fileiput" type="file">
                                    <input class="step-hide-input" name="cover_uri"  type="text">
                                    <span name="coverCurr"></span>
                                    
                                </div>
                            </div>
                            <p class="submit-modal-tips">推荐上传正方形封面</p>
                            <div class="submit-modal-group submit-modal-group--tips">
                                <label for="music" class="submit-modal-label label-not-null">视频文件</label>
                                <div type="text" class="submit-modal-file">
                                    <div class="submit-modal-button">上传视频文件</div>

                                    <!-- 视频文件 -->
                                    <input id="video-file-name" class="submit-modal-name" disabled="disabled" name="musicName">
                                    <input onchange="addVideo(this)" name="file"  class="submit-modal-fileiput" type="file">
                                    <input class="step-hide-input" name="song_uri"  type="text">
                                    <span name="videoCurr"></span>
                                </div>
                            </div>
                            
                            
                            
                            <p class="submit-modal-tips">支持mp3/wav格式,且音质在320kb以上,文件不超过200MB</p>

                            <!-- 上传按钮 -->
                            <div class="submit-modal-group" id="if-campus" style="margin-bottom: 5px;">
                                <label for="original_type" class="submit-modal-label label-not-null">点击这里上传视频</label>
                                <input class="step-button" onclick="uploadVideoAndCover()" value="上传视频和封面"  type="button">
                            </div>


                            <div class="submit-step-button-group">
                                <input class="step-button" value="确认添加"  type="submit">
                                <div class="step-button" id="hideModalBtn">取消</div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 跨域请求 -->
        <a href="http://localhost:8081/Fileio/FileAction_test">这里</a>
        
        <form action="http://localhost:8081/Fileio/FileAction_test" method="post">
            <input type="text" name="test">
            <input type="submit">
        </form>
        
        <form id="formtest" action="http://localhost:8081/Fileio/FileAction_fileTest" method="post" enctype="multipart/form-data">
            <input type="file" name="upload">
            <input type="submit">
        </form>
        
        <script src="//imgcache.qq.com/open/qcloud/js/vod/sdk/ugcUploader.js"></script>
        <script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" th:inline="javascript">
            
//             初始化
            var videoFile = null;
            var coverFile = null;
        
            //得到加密后的字符 串
            var getSignature = function(callback)
            {
                $.ajax({
                    
                    url:[[@{~/sign}]],
                    type:"POST",
                    success:function(result)
                    {
                        callback(result);
                    }
                    
                })
            }
            
            //当videoinput改变时会调用这个函 数
            function addVideo(e)
            {
//                 alert(e.files[0].name);
                videoFile=e.files[0];
                $("#video-file-name").val(e.files[0].name);
            }
            
            
            //当cover改变时会调用这个函 数
            function addCover(e)
            {
//                 alert(e.files[0].name);
                coverFile = e.files[0];
                $("#cover-file-name").val(e.files[0].name);
            }
        
            function uploadVideoAndCover()
            {
                
                //$.post(
                //action的地址
                //"http://127.0.0.1:8081/Fileio/FileAction_ajax",
                //提交的数据
                //{"test":"Gary"},
                //回调函数
                //function(data)
                //{
                //    
                //},
                //数据格式
                //"json"
                //)
                
                //表单数 据
                var formData = new FormData($("#formtest")[0]);
                
                $.ajax({
                    type:"POST",
                    url:"http://127.0.0.1:8081/Fileio/FileAction_fileTestAjax",
                    async:false,
                    cache:false,
                    //传入的数据
                    data:formData,
                    //是否处理数据
                    processData:false,
                    //内容类型
                    contentType:false,
                    dataType:"json",
                    success:function(data)
                    {
                        
                    },
                    error:function(data)
                    {
                        
                    }
                })
                
                
                //upload();    
            }
            
            //上传视频和封 面
            function upload()
            {
                alert(videoFile.name);
                alert(coverFile.name);
                qcVideo.ugcUploader.start({    
                    //视频
                    videoFile:videoFile,
                    //封面
                    coverFile:coverFile,
                    //sign
                    getSignature:getSignature,
                    //allowAudio
                    allowAudio:1,
                    
                    success:function(result)
                    {
                        
                    },
                    errer:function(result)
                    {
                        alert("上传失败");
                    },
                    progress:function(result)
                    {
                        $("[name=videoCurr]").text(Math.floor(result.curr*100)+"%");
                        $("[name=coverCurr]").text(Math.floor(result.curr*100)+"%");
                    },
                    finish:function(result)
                    {
                        alert("上传成功");
                    }
                    
                    
                })

            }
            
            
            $(function() {
                require('web:common/utils/promise.polyfill');
                require('web:page/musician/apply/submitMusic/submit');
    })</script>
      <script>window.Raven && Raven.config('//key@m.toutiao.com/log/sentry/v2/96', {
        tags: {
            bid: 'douyin_web',
            pid: 'musician_apply_submit'
        }
    }).install();
      </script>
    </div>
    <script>window.Raven && Raven.config('//key@m.toutiao.com/log/sentry/v2/96', {
        tags: {
            bid: 'douyin_web',
            pid: 'musician_apply_submit'
        }
    }).install();</script>
    <script src="register-add-music_files/index_7a47cdc.js"></script>
    <script src="register-add-music_files/es6-promise.js"></script>
    <script src="register-add-music_files/promise.js"></script>
    <script src="register-add-music_files/file_f9a5ca7.js"></script>
    <script src="register-add-music_files/form_ebcf55b.js"></script>
    <script src="register-add-music_files/toast_d6fd98c.js"></script>
    <script src="register-add-music_files/dropkick_7018fdd.js"></script>
    <script src="register-add-music_files/xss_6a7474d.js"></script>
    <script src="register-add-music_files/submit_9e6c0af.js"></script>
</body>
</html>
register-add-music.html

 

package com.Gary.web;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.Gary.domain.Lfile;
import com.Gary.service.FileService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class FileAction extends ActionSupport{

    //上传的文件
    private File upload;
    //文件的类型
    private String uploadContentType;
    //文件的名称
    private String uploadFileName;
    
    private FileService fileService;
    
    private String test;
    
    public String fileTestAjax() throws Exception{
        
        System.out.println(upload);
        System.out.println(uploadContentType);
        System.out.println(uploadFileName);
        
        ServletActionContext.getResponse().getWriter().write("{\"success\":"+true+"}");
        return null;
    }
    
    
    public String fileTest() throws Exception{
        System.out.println(upload);
        System.out.println(uploadContentType);
        System.out.println(uploadFileName);
        
        
        return "index";
    }
    
    //带参数的ajax跨域炒作
    public String ajax() throws Exception{
        
        System.out.println(test);
        
        ServletActionContext.getResponse().getWriter().write("{\"success\":"+true+"}");
        return null;
    }
    

    //实现跨域请求  是否可以调用这个函数
    public String test() throws Exception
    {
        System.out.println("跨域请求!!");
        System.out.println(test);
        return "index";
    }
    
    //查找所有的文件
    public String getData() throws Exception {
    
        List<Lfile> list =  fileService.findAllLfile();
        
        ActionContext.getContext().put("list", list);
        
        return "index";
    
    }
    
    
    public String addFile() throws Exception {
        
//        System.out.println(upload);
//        System.out.println(uploadContentType);
//        System.out.println(uploadFileName);
        
        //保存到数据库
        
        //文件保存到项目
        //文件保存位置
        String path = ServletActionContext.getServletContext().getRealPath("/images");
        //创建一个file文件
        File file = new File(path);
        //路径如果不存在,要手动make一下
        if(!file.exists())
        {
            file.mkdir();
        }
        //文件拷贝的格式
        FileUtils.copyFile(upload, new File(file,uploadFileName));
        System.out.println(path);
        
        //保存到数据库
        Lfile lfile = new Lfile();
        lfile.setFilename(uploadFileName);
        lfile.setFiletype(uploadContentType);
        lfile.setUrl(path+"\\"+uploadFileName);
        
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat  format = new SimpleDateFormat("yyyy-MM-dd");
        String createtime = format.format(date);
        
        lfile.setCreatetime(createtime);
        
        //判断数据库中是否存在相同名字的文件
        boolean success =fileService.JudgeLfilename(uploadFileName);
        //如果有相同的filename我们就不进行插入
        if(success) {
            fileService.addFile(lfile);
        }
        
        
        return "default";
    }

    
    public FileService getFileService() {
        return fileService;
    }


    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }


    public File getUpload() {
        return upload;
    }


    public void setUpload(File upload) {
        this.upload = upload;
    }


    public String getUploadContentType() {
        return uploadContentType;
    }


    public void setUploadContentType(String uploadContentType) {
        this.uploadContentType = uploadContentType;
    }


    public String getUploadFileName() {
        return uploadFileName;
    }


    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }
}
FileAction.java

 

posted @ 2019-02-06 23:13  Cynical丶Gary  阅读(980)  评论(0编辑  收藏  举报