springboot2.0上傳檔案(視訊,圖片)到伺服器硬碟,並儲存路徑至mysql,返回可直接訪問的url
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目錄下:
相關文章
- .Net之使用Jquery Ajax通過FormData物件非同步提交圖片檔案到服務端儲存並返回儲存的圖片路徑jQueryORM物件非同步服務端
- 【轉】mysql儲存圖片技術決定:儲存二進位制檔案還是隻儲存圖片相對路徑,圖片放在硬碟上面?MySql硬碟
- 微信小程式上傳多圖到伺服器並獲取返回的路徑微信小程式伺服器
- laravel上傳圖片路徑問題Laravel
- MultipartFile上傳圖片儲存伺服器伺服器
- Excel 讀取圖片並獲取儲存路徑Excel
- Go後臺對圖片base64解碼,並儲存至檔案伺服器。Go伺服器
- 上傳視訊介面:使用for迴圈,把視訊從本地上傳到伺服器,生成視訊和圖片地址,並儲存到log檔案A1伺服器
- 安卓上傳圖片到伺服器並儲存到電腦本地安卓伺服器
- springboot專案上傳儲存圖片到七牛雲伺服器Spring Boot伺服器
- React Native 上傳圖片至七牛雲端儲存React Native
- Java實現圖片上傳到伺服器,並把上傳的圖片讀取出來Java伺服器
- Android:MediaCodeC硬編碼解碼視訊,並將視訊幀儲存為圖片檔案Android
- 將圖片上傳到gitee伺服器,md不依賴於本地路徑:Gitee伺服器
- 開發日記之把url的檔案上傳至伺服器伺服器
- 圖片檔案上傳
- 直播網站原始碼,上傳圖片到專案目錄並將相對路徑儲存到資料庫網站原始碼資料庫
- .net上傳大型視訊檔案到伺服器,解決方案伺服器
- webpack:url-loader 圖片路徑問題Web
- 如何將MAC的檔案儲存至NAS網路儲存?Mac
- 使用axios上傳檔案到阿里雲物件檔案儲存伺服器ossiOS阿里物件伺服器
- 短視訊帶貨原始碼,儲存圖片到相簿/相簿原始碼
- 圖片等檔案上傳到阿里雲的STS臨時授權訪問的配置詳解阿里
- 短視訊原始碼,視訊轉為圖片儲存原始碼
- FileReader與URL.createObjectURL實現圖片、視訊上傳預覽Object
- ASP儲存遠端圖片檔案到原生程式碼
- 【檔案上傳繞過】路徑拼接問題導致上傳漏洞
- [開源專案] Laravel 圖片上傳元件,支援直傳雲端儲存Laravel元件
- 網路請求(一般請求,上傳圖片,上傳視訊)
- 請問個位大俠上傳圖片的路徑如何設定???
- Alfred Workflow 一鍵上傳圖片到 GitHub 返回 MarkdownAlfredGithub
- 簡單檔案的上傳與儲存
- 上傳檔案時路徑總是C:\fakepath\的問題
- 快速理解Android檔案儲存路徑Android
- php圖片上傳之分散式儲存FastDFSPHP分散式AST
- 小程式踩坑記錄-上傳圖片及canvas裁剪圖片後上傳至伺服器Canvas伺服器
- iOS圖片,視訊上傳&視訊內容旋轉iOS
- 有關laravel 上傳圖片訪問404的問題Laravel