1. 程式人生 > >Rome was not built in one day

Rome was not built in one day

FastDFS的理解及安裝請參考:

這裡介紹的是SpringBoot整合FastDFS實現上傳檔案的功能;

(1)在pom.xml中引入一個好心人在maven倉庫中提交的fastdfs-java的客戶端

<dependency>
    <groupId>com.github.tobato</groupId>
    <artifactId>fastdfs-client</artifactId>
    <version>1.25.3-RELEASE</version>
</dependency>

(2)在application.yml中配置

# 分散式檔案系統FDFS配置
fdfs:
  soTimeout: 1500 #socket連線超時時長
  connectTimeout: 600 #連線tracker伺服器超時時長
  resHost: 192.168.1.11
  storagePort: 80
  thumbImage: #縮圖生成引數,可選
      width: 150
      height: 150
  trackerList: #TrackerList引數,支援多個,我這裡只有一個,如果有多個在下方加- x.x.x.x:port
    - 192.168.1.11:22122
spring:
  http:
    multipart:
      max-file-size: 100MB # 最大支援檔案大小
      max-request-size: 100MB # 最大支援請求大小

(3)配置類(用於獲取storage資訊)

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FdfsConfig {

    @Value("${fdfs.resHost}")
    private String resHost;

    @Value("${fdfs.storagePort}")
    private String storagePort;

    public String getResHost() {
        return resHost;
    }

    public void setResHost(String resHost) {
        this.resHost = resHost;
    }

    public String getStoragePort() {
        return storagePort;
    }

    public void setStoragePort(String storagePort) {
        this.storagePort = storagePort;
    }
}

(4)增加配置類(此類裡面什麼都不需要做,也可以把@Import和@EnableMBeanExport放在啟動類上,我是感覺啟動類上放太多東西不好看就增加了一個配置類)

import com.github.tobato.fastdfs.FdfsClientConfig;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.context.annotation.Import;
import org.springframework.jmx.support.RegistrationPolicy;

/**
 * 匯入FastDFS-Client元件
 */
@Configuration
@Import(FdfsClientConfig.class)//註解,就可以擁有帶有連線池的FastDFS Java客戶端了
@EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING)// 解決jmx重複註冊bean的問題
public class FdfsConfiguration {
}

(5)上傳工具類

import java.io.IOException;
import java.io.InputStream;

import com.li.original.common.constant.GlobalConstants;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

/**
 * 工具類
 */
@Component
public class FastDFSClientWrapper {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsConfig fdfsConfig;
    
   public String uploadFile(MultipartFile file) throws IOException {
       StorePath storePath = storageClient.uploadFile((InputStream)file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
       return getResAccessUrl(storePath);
   }

    /**
     * 封裝檔案完整URL地址
     * @param storePath
     * @return
     */
   private String getResAccessUrl(StorePath storePath) {
       String fileUrl = GlobalConstants.HTTP_PRODOCOL + fdfsConfig.getResHost() + ":" + fdfsConfig.getStoragePort() + "/" + storePath.getFullPath();
       return fileUrl;
   }
}

(6)控制類

import com.li.original.common.fdfs.FastDFSClientWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
@RequestMapping("/upload")
public class UploadController {


    @Autowired
    private FastDFSClientWrapper dfsClient;
    @GetMapping("/")
    public String index() {
        return "upload/upload";
    }

    @PostMapping("/fdfs_upload")
    public String fdfsUpload(@RequestParam("file") MultipartFile file,
                             RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:/upload/uploadStatus";
        }

        try {
            String fileUrl= dfsClient.uploadFile(file);
            redirectAttributes.addFlashAttribute("message",
                    "You successfully uploaded '" + fileUrl + "'");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/upload/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        return "upload/uploadStatus";
    }

}

(7)upload.ftl(繼承的freemark,放在template/upload下面,下面的uploadStatus.ftl也是)

<!DOCTYPE html>
<html>
<body>

<h1>Spring Boot file upload example</h1>

<form method="POST" action="fdfs_upload" enctype="multipart/form-data">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

</body>
</html>

(8)uploadStatus.ftl

<!DOCTYPE html>
<html>
<body>

<h1>Spring Boot - Upload Status</h1>

<div>
    <h2>${message}</h2>
</div>

</body>
</html>

(9)增加一個上傳檔案異常捕獲類

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice//全域性異常處理
public class GlobalExceptionHandler {

     /**
     * 捕獲上傳檔案異常
     * @param e
     * @return
     */
    //https://jira.spring.io/browse/SPR-14651
    //4.3.5 supports RedirectAttributes redirectAttributes
    @ExceptionHandler(MultipartException.class)
    public ModelAndView handleError1(MultipartException e) {
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", "上傳檔案異常");
        mav.setViewName("upload/uploadStatus");
        return mav;
    }

}

相關推薦

盧小喵的學習筆記(Rome was not built in one day.)

FreeRTOS學習筆記 作為一個輕量級的作業系統,FreeRTOS 提供的功能包括:任務管理、時間管理、訊號量、訊息佇列、記憶體管理、記錄功能等,可基本滿足較小系統的需要。本專欄致力於分析FreeRTOS的內部實現,並分享Fre

Rome was not built in one day

FastDFS的理解及安裝請參考:這裡介紹的是SpringBoot整合FastDFS實現上傳檔案的功能;(1)在pom.xml中引入一個好心人在maven倉庫中提交的fastdfs-java的客戶端<dependency>     <groupId>c

【Caius的部落格】A day does not come again, one day is difficult. In time to encourage, time does not wait for people.

A day does not come again, one day is difficult. In time to encourage, time does not wait for people...

Package gtk+-3.0 was not found in the pkg-config search path

path 二進制 all 項目 有時 rpm fedora ack share 問題描述:   在fedora21系統上通過rpmbuild構建fcitx的二進制包時出現以上錯誤,經老程序員指點:“是相應的開發包沒有安裝” 解決辦法:   yum installl gtk3

Ubuntu 16.04 LTS 安裝libvips出現”Package vips was not found in the pkg-config search path”

arp dir exp export ron per gconf 部署 director 使用libvips來操作圖像,libvips的部署參考一個Node.js工程:https://github.com/lovell/sharp 在MAC下安裝很順利,到Linux環境下(

python version 2.7 required,which was not found in the registry

.html except http nco com name desc log all # # script to register Python 2.0 or later for use with win32all # and other extensions that

安裝第三方庫 報錯Python version 2.7 required, which was not found in the registry

try 三方庫 64位 req not 安裝 window 是我 found 我的Windows 系統是64位 這個問題有人說是註冊表沒有 ,手動註冊了一下就好了,但是我註冊的時候運行報錯。 那麽我的做法是: 刪掉本機所有安裝過得python , 1、 先進入控制面板,刪除

安裝第三方庫出現 Python version 2.7 required, which was not found in the registry

prefix another odin light admin urn utf n! .py 安裝第三方庫出現 Python version 2.7 required, which was not found in the registry 建立一個文件 register.

Python version 3.3 required, which was not found in the registry

() fix core can war 安裝 錯誤 -c gpa python registry函數語法 在windows下安裝numpy的時候, 出現了"Python version 3.3 required, which was not found in the re

java: System Java Compiler was not found in classpath: java.lang.ClassNotFoundException: com.s錯誤改正方法

剛開始編譯java 時候,什麼jdk也都安裝完畢了,但是老是出現 老是出現這個問題。現在出來寫一個博文進行記錄一下。        我的編譯環境:jdk版本:1.8;win7;編輯器:IntelliJ Idea ; 解決方法:

安裝Centos 6.4提示找不到安裝檔案 The centos disc was not found in any of your drives.Please insert the centos d

【1】安裝Centos 6.4提示找不到安裝檔案 The centos disc was not found in any of your drives.Please insert the centos disc and press OK to retry  解決方法: 把CD

hive啟動報錯之2、The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH.

報錯資訊如下: [[email protected] bin]$ ./hive Missing Hive Execution Jar: /opt/soft/apache-hive-1.1.0-cdh5.7.0-bin/lib/hive-exec-*.jar 考慮的

執行Spark SQL報The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH.

想啟動spark-sql,結果報了 Caused by: org.datanucleus.store.rdbms.connectionpool.DatastoreDriverNotFoundExcept

ndkbuild c++ string 'string' is not a member of 'std' 'string' was not declared in this scope

最近使用ndk時, #include <string> ndkbuild編譯後報錯:fatal error: string: No such file or directory #include <string.h> std::string 編

錯誤資訊was not declared in this scope

“was not declared in this scope”是一個錯誤資訊,在編譯的時候會遇到。其含義為識別符號在其出現的地方是未被定義的。 出現該錯誤的時候,會同時把未定義的變數名顯示出來。比如如下程式: int main() { printf("%d",i);//這個i是

eclipse svn外掛解除安裝 重新安裝 Subclipse解除安裝安裝 The project was not built since its build path is incomplete This client is too old to wor

安裝外掛的原則就是,要按照規則,外掛與本地的svn版本要一致, 這樣子本地和eclipse上面就可以無縫使用,不會出現問題 1.解除安裝eclipse  svn外掛   2,安裝新版的svn外掛 2.1,下載 找到網址或者zip包 下

Python Version 2.7 required which was not found in the registry 問題解決

 今天在安裝numpy時,出現了Python Version 2.7 required which was not found in the registry錯誤,解決方案如下。   Python的一些第三方庫只到登錄檔的HKEY_LOCAL_MACHINE\SO

Android -- the project was not built due to a resource exists with a different case...

進行編碼時,工程前面莫名有個紅X,正當百思不得其解時,發現在[problems]下有如下的訊息輸出 ------ the project was not built due to a resource exists with a different case... ---

sparksql啟動報錯The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH

  要啟動sparksql並訪問到Hive,有兩個步驟: 1、將$HIVE_HOME/conf/hive-site.xml拷貝到$SPARK_HOME/conf下 2、配置MySQL驅動包,將MySQL驅動包放在一個自定義目錄下,在$SPARK_HOME/conf裡面的spark-def

處理VS2010+qt4.8.6下編譯不報錯誤,而Linux下報錯:error: 'nullptr' was not declared in this scope

今天處理一個同事在VS2010+qt4.8.6下編寫的程式(能夠正確編譯並執行) 我需要將這個程式移植到arm板上,於是在Linux下對此程式進行交叉編譯 於是,問題來了 這個錯誤提示是:nullptr在當前作用域沒有被宣告。 稍作分析,這個nullptr並不是程式定義的,