如何通過JAVA代碼上傳圖片和視頻到阿里雲服務器


第一步:需要在阿里雲服務器上安裝Docker(在這里我就不詳細說明如何在阿里雲安裝Docker)

第二步:拉取鏡像並啟動 docker run -d --restart=always --privileged=true --net=host --name=fastdfs -e IP=192.168.14.1 -e WEB_PORT=80 -v ${HOME}/fastdfs:/var/local/fdfs registry.cn-beijing.aliyuncs.com/tianzuo/fastdfs

其中-v ${HOME}/fastdfs:/var/local/fdfs是指:將${HOME}/fastdfs這個目錄掛載到容器里的/var/local/fdfs這個目錄里。所以上傳的文件將被持久化到${HOME}/fastdfs/storage/data里,IP 后面是自己的服務器公網ip或者虛擬機ip-e WEB_PORT=80 指定nginx端口

 

//進入容器

docker exec -it fastdfs /bin/bash

//創建文件

echo "Hello FastDFS!">index.html

//測試文件上傳

fdfs_test /etc/fdfs/client.conf upload index.html

 

阿里雲控制台開放端口號

 

 

第三步:新建SpingBoot項目引入fastdfs依賴

<dependency>

            <groupId>com.github.tobato</groupId>

            <artifactId>fastdfs-client</artifactId>

            <version>${fastdfs-client.version}</version>

        </dependency>

創建application.yml文件

fdfs:

  so-timeout: 2500

  connect-timeout: 600

  thumb-image:

      width: 100

      height: 100

  tracker-list:          # tracker服務配置地址列表

      - 自己服務器IP不帶http:22122

upload:

  base-url: http://自己服務器IP/

 allow-types:

    - image/jpeg

    - image/png

    - image/bmp

    - image/gif

    - video/mp4

第四步:創建測試類進行文件上傳

@Component

@EnableConfigurationProperties(UploadProperties.class)

public class Upload {

 

 

    private Log log= LogFactory.getLog(UploadService.class);

 

    @Autowired

    private FastFileStorageClient storageClient;

 

    @Autowired

    private UploadProperties prop;

 

    public String uploadImage(MultipartFile file) {

        // 校驗文件類型

        String contentType = file.getContentType();

        if (!prop.getAllowTypes().contains(contentType)) {

            throw new RuntimeException("文件類型不支持");

        }

        // 校驗文件內容

        try {

// 校驗文件內容

             InputStream inputStream = file.getInputStream() ;

            if (inputStream == null ) {

                throw new RuntimeException("上傳文件有問題");

            }

        } catch (IOException e) {

            log.error("校驗文件內容失敗....{}", e);

            throw new RuntimeException("校驗文件內容失敗"+e.getMessage());

        }

 

        try {

            // 上傳到FastDFS

            // 獲取擴展名

 

            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");

           

            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);

            

            return prop.getBaseUrl() + storePath.getFullPath();

        } catch (IOException e) {

            log.error("【文件上傳】上傳文件失敗!....{}", e);

            throw  new RuntimeException("【文件上傳】上傳文件失敗!"+e.getMessage());

        }

}

 

 

 

 

@ConfigurationProperties(prefix = "upload")

@Data

public class UploadProperties {

 

 private String baseUrl;

 

 private List<String> allowTypes;

 

如果你的SpringBoot2.0以上的版本在文件上傳時可能會拋出如下異常:

the request was rejected because its size (35678390) exceeds the configured maximum (10485760)

 

此時添加一個配置類:

@Configuration

public class MultipartConfig {

 

@Bean

 public MultipartConfigElement multipartConfigElement() {

       MultipartConfigFactory factory = new MultipartConfigFactory();

       //文件最大10M,DataUnit提供5中類型B,KB,MB,GB,TB

       factory.setMaxFileSize(DataSize.of(200, DataUnit.MEGABYTES));

       // 設置總上傳數據總大小10M

       factory.setMaxRequestSize(DataSize.of(200, DataUnit.MEGABYTES));

       return factory.createMultipartConfig();

   }

 

最后創建Controller

@RequestMapping("/doUpload")

    public Map<String, Object> doUpload (MultipartFile mf) {

        Map<String, Object> map = new HashMap<String,Object>() ;

        String image = this.uploadService.uploadImage(mf);

        map.put("path",image) ;

        return map ;

    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM