springboot2.0上傳檔案(視訊,圖片)到伺服器硬碟,並儲存路徑至mysql,返回可直接訪問的url

qq_37164847發表於2018-08-14

1.預覽:

1.1

1.2

 

1.3

複製這個url到瀏覽器:

上傳視訊的話,複製視訊url到瀏覽器:

2.程式碼相關部分:

先建立一個表shipins:

name:上傳的檔名字,lujing:檔案在硬碟的路徑,url:可直接訪問的連結。

idea建立一個springboot專案:

1.pom.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.shipin</groupId>
   <artifactId>shangchuan</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>war</packaging>
   <name>shangchuan</name>
   <description>Demo project for Spring Boot</description>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.0.4.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <!-- spring boot web支援:mvc,aop... -->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
         <!-- 過濾springboot預設嵌入式tomcat外掛 -->
         <!--<exclusions>-->
            <!--<exclusion>-->
               <!--<groupId>org.springframework.boot</groupId>-->
               <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
            <!--</exclusion>-->
         <!--</exclusions>-->
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
      </dependency>
      <!--thymeleaf模板-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-thymeleaf</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-devtools</artifactId>
         <optional>true</optional>
      </dependency>
      <!--MyBatis依賴jar包和MySQL連線相關的jar包-->
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
      </dependency>
      <dependency>
         <groupId>org.mybatis.spring.boot</groupId>
         <artifactId>mybatis-spring-boot-starter</artifactId>
         <version>1.3.1</version>
      </dependency>

      <!--打包新增的依賴-->
      <!--新增發布依賴-->
      <!--<dependency>-->
         <!--<groupId>org.springframework.boot</groupId>-->
         <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
         <!--<scope>provided</scope>-->
      <!--</dependency>-->
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>


</project>

2.application.properties檔案:

# url path
#server.port=8088
#server.servlet.context-path=/shipin

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type
spring.thymeleaf.servlet.content-type=text/html

# 開發階段務必關閉快取 (=false)
spring.thymeleaf.cache=false

#最大檔案大小。值可以使用字尾“MB”或“KB”。指示兆位元組或千位元組大小。
spring.servlet.multipart.max-file-size=-1
# 最大請求大小可以是mb也可以是kb
spring.servlet.multipart.max-request-size=-1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/表名?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=mysql賬號
spring.datasource.password=mysql密碼
logging.level.com.shengquan.registeradmin.dao=debug
#配置外部訪問檔案(把上傳的圖片視訊檔案放到E盤下的fileUpload資料夾下)
cbs.imagesPath=file:/E:/fileUpload/
#com.yangyouqi: ${server.port}
#spring.jmx.enabled=false

3.上傳配置類:

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

import javax.servlet.MultipartConfigElement;

//上傳配置類
//圖片放到/F:/fileUpload/後,從磁碟讀取的圖片資料scr將會變成images/picturename.jpg的格式
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
//public class WebAppConfig extends WebMvcConfigurationSupport {
    /**
     * 在配置檔案中配置的檔案儲存路徑
     */
    @Value("${cbs.imagesPath}")
    private String mImagesPath;

    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //檔案最大KB,MB
        factory.setMaxFileSize("1024MB");
        //設定總上傳資料總大小
        factory.setMaxRequestSize("1024MB");
        return factory.createMultipartConfig();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            System.out.print("1.上傳配置類imagesPath=="+imagesPath+"\n");
            if(imagesPath.indexOf(".jar")>0){
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
                imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            mImagesPath = imagesPath;
        }
        System.out.print("imagesPath============="+mImagesPath+"\n");
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath============="+mImagesPath+"\n");
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        // TODO Auto-generated method stub
        System.out.print("2.上傳配置類mImagesPath=="+mImagesPath+"\n");
        super.addResourceHandlers(registry);
    }

}

啟動類:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.boot.builder.SpringApplicationBuilder;
//import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
//import org.springframework.web.WebApplicationInitializer;

@SpringBootApplication
public class ShangchuanApplication {
//public class ShangchuanApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

// // 打包war需要這個啟動類,釋出到伺服器上
// @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
//    System.out.print("視訊上傳專案啟動類2.==="+"\n");
//    return application.sources(ShangchuanApplication.class);
// }

   public static void main(String[] args) {
      System.out.print("視訊上傳專案啟動類1.==="+"\n");
      SpringApplication.run(ShangchuanApplication.class, args);
   }

}

4.專案整體結構:

5.dao層:

import com.shipin.shangchuan.model.Shipin;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper
@Component
public interface ShiPinDao {

    //插入
    @Insert({"insert into shipins (name,lujing,url) values (#{name},#{lujing},#{url})"})
    public int insertUrl(@Param("name")String name,@Param("lujing")String lujing,@Param("url")String url);

    //查詢
    @Select("select * from shipins")
    public List<Shipin> selectShipin();
}

6.model層:

public class Shipin {

    private int id;
    private String url;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

}

7.service層:

import com.shipin.shangchuan.dao.ShiPinDao;
import com.shipin.shangchuan.model.Shipin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
@Component
public class ShiPinService {

    @Autowired
    private ShiPinDao shiPinDao;

    //插入
    public int insertUrl(String name,String lujing,String url){
        System.out.print("開始插入=name=="+name+"\n");
        System.out.print("開始插入=lujing=="+lujing+"\n");
        System.out.print("開始插入=url=="+url+"\n");
        int jieguo=shiPinDao.insertUrl(name,lujing,url);
        System.out.print("插入結果==="+jieguo+"\n");
        return jieguo;
    }
    //查詢
    public List<Shipin> selectShipin(){
        List<Shipin> shipins=shiPinDao.selectShipin();
        return  shipins;
    }
}

8.controller層:

頁面跳轉類:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FileUploadController {

    //訪問路徑為:http://localhost:8080/file

    @RequestMapping("/file")

    public String file(){
        System.out.print("================請求路徑===跳轉file頁面====="+"\n");
        return "/file";

    }

//    @RequestMapping("/shangchuan")
//
//    public String shangchuan(){
//        System.out.print("================請求路徑===跳轉index頁面====="+"\n");
//        return "/index";
//
//    }
}

處理上傳類:

import com.shipin.shangchuan.model.Shipin;
import com.shipin.shangchuan.service.ShiPinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
//@RequestMapping("/file")
public class MyfileCOntroller {

    @Autowired
    private ShiPinService shiPinService;

    private String  url;

    @RequestMapping(value="/uploadFile",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile file) {

        System.out.print("上傳檔案==="+"\n");
        //判斷檔案是否為空
        if (file.isEmpty()) {
            return "上傳檔案不可為空";
        }


        // 獲取檔名
        String fileName = file.getOriginalFilename();
//        System.out.print("上傳的檔名為: "+fileName+"\n");

        fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        System.out.print("(加個時間戳,儘量避免檔名稱重複)儲存的檔名為: "+fileName+"\n");


        //加個時間戳,儘量避免檔名稱重複
        String path = "E:/fileUpload/" +fileName;
        //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        //檔案絕對路徑
        System.out.print("儲存檔案絕對路徑"+path+"\n");

        //建立檔案路徑
        File dest = new File(path);

        //判斷檔案是否已經存在
        if (dest.exists()) {
            return "檔案已經存在";
        }

        //判斷檔案父目錄是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        try {
            //上傳檔案
            file.transferTo(dest); //儲存檔案
            System.out.print("儲存檔案路徑"+path+"\n");
            //url="http://你自己的域名/專案名/images/"+fileName;//正式專案
            url="http://localhost:8080/images/"+fileName;//本地執行專案
            int jieguo= shiPinService.insertUrl(fileName,path,url);
            System.out.print("插入結果"+jieguo+"\n");
            System.out.print("儲存的完整url===="+url+"\n");

        } catch (IOException e) {
            return "上傳失敗";
        }

        return "上傳成功,檔案url=="+url;
    }

    //查詢
    @RequestMapping("/chaxun")
    public String huizhiDuanxin(Model model){
          System.out.print("查詢視訊"+"\n");
          List<Shipin> shipins=shiPinService.selectShipin();
          System.out.print("查詢到的視訊數量=="+shipins.size()+"\n");
          model.addAttribute("Shipins", shipins);

        return "/filelist";
    }

}

9.頁面:

file.html頁面

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml"xmlns:th="http://www.thymeleaf.org"

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

    <title>Hello World!</title>

</head>

<body>
<div style="text-align: center;margin-top: 50px">
    <form action="uploadFile" method="post" enctype="multipart/form-data">
        <p><input type="file" name="fileName"/></p>
        <p><input type="submit" value="上傳視訊"/></p>
    </form>
    <form action="chaxun" >
        <p><input type="submit" value="查詢視訊"/></p>
    </form>
</div>
</body>

</html>

filelist.html頁面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>視訊列表</title>
</head>
<body>
視訊列表
<div>
    <ul>
        <li th:each="Shipin:${Shipins}">
            <p>ID:<span th:text="${Shipin.id}"></span></p>
            <p>視訊url======<span th:text="${Shipin.url}"></span></p>
        </li>
    </ul>
</div>
</body>
</html>

最後執行專案,在瀏覽器輸入:

http://localhost:8080/file進入上傳頁面

專案如果打包war釋出到伺服器的tomcat上,

如果WebAppConfig這個類引起錯誤,改成
public class WebAppConfig extends WebMvcConfigurationSupport 其餘不變就可以了。

打包時:

把pom.xml檔案中的這兩個註釋掉的放開,然後application類改成:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.web.WebApplicationInitializer;

@SpringBootApplication
public class ShangchuanApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

   // 打包war需要這個啟動類,釋出到伺服器上
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder application){
      System.out.print("視訊上傳專案啟動類2.==="+"\n");
      return application.sources(ShangchuanApplication.class);
   }

   public static void main(String[] args) {
      System.out.print("視訊上傳專案啟動類1.==="+"\n");
      SpringApplication.run(ShangchuanApplication.class, args);
   }

}

最後點選:idea右側的:

會打包成war,在專案的target目錄下:

專案下載地址:https://gitee.com/xuhaiyan/sg.git

相關文章