最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot實(shí)現(xiàn)OneDrive文件上傳的詳細(xì)步驟

 更新時(shí)間:2024年02月18日 09:36:12   作者:木芒果呀  
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)OneDrive文件上傳的詳細(xì)步驟,文中通過(guò)代碼示例和圖文講解的非常詳細(xì),對(duì)大家實(shí)現(xiàn)OneDrive文件上傳有一定的幫助,需要的朋友可以參考下

SpringBoot實(shí)現(xiàn)OneDrive文件上傳

源碼

OneDriveUpload: SpringBoot實(shí)現(xiàn)OneDrive文件上傳

獲取accessToken步驟

參考文檔:針對(duì) OneDrive API 的 Microsoft 帳戶授權(quán) - OneDrive dev center | Microsoft Learn

1.訪問(wèn)Azure創(chuàng)建應(yīng)用Microsoft Azure,使用微軟賬號(hào)進(jìn)行登錄即可!

2.進(jìn)入應(yīng)用創(chuàng)建密碼

3.獲取code

通過(guò)訪問(wèn)(必須用瀏覽器,通過(guò)地址欄輸入的方式):https://login.live.com/oauth20_authorize.srf?client_id=你的應(yīng)用程序(客戶端) ID&scope=files.readwrite offline_access&response_type=code&redirect_uri=http://localhost:8080/redirectUri

以上步驟都正確的情況下,會(huì)在地址欄返回一個(gè)code,也就是M.C105.........

4.獲取accessToken

拿到code后就可以拿token了,通過(guò)對(duì)https://login.live.com/oauth20_token.srf 發(fā)起POST請(qǐng)求并傳遞相關(guān)參數(shù),這一步需要用接口調(diào)試工具完成!

其中client_id和redirect_uri與上面相同,client_secret填剛剛創(chuàng)建的密鑰,code就是剛剛獲取到的code,grant_type就填authorization_code即可!

正常情況下訪問(wèn)后就能得到access_token,然后把a(bǔ)ccess_token放在springboot的配置文件中!

代碼實(shí)現(xiàn)步驟

1. 新建一個(gè)springBoot項(xiàng)目,選擇web依賴即可!

2. 引入相關(guān)依賴

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.16</version>
        </dependency>
 
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.0</version>
        </dependency>

3.編寫(xiě)文件上傳接口類(lèi)

參考文檔:上傳小文件 - OneDrive API - OneDrive dev center | Microsoft Learn

import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
 
/**
 * 文件上傳到OneDrive并將文件信息存儲(chǔ)到Excel文件中
 */
@Controller
public class FileSyncController {
    private static final Logger logger = LoggerFactory.getLogger(FileSyncController.class);
    private static final String ONE_DRIVE_BASE_URL = "https://graph.microsoft.com/v1.0/me/drive/root:/uploadfile/";
 
    @Value("${onedrive.access-token}")
    private String ACCESS_TOKEN;
 
 
    @PostMapping("/upload")
    public void uploadFileToDrive(@RequestParam("file") MultipartFile file, HttpServletResponse httpServletResponse) throws IOException {
        if (file.isEmpty()) {
            throw new RuntimeException("文件為空!");
        }
 
        String fileName = file.getOriginalFilename();
        String oneDriveUploadUrl = ONE_DRIVE_BASE_URL + fileName + ":/content";
 
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setBearerAuth(ACCESS_TOKEN);
 
        HttpEntity<byte[]> requestEntity;
        try {
            byte[] fileBytes = file.getBytes();
            requestEntity = new HttpEntity<>(fileBytes, headers);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
 
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(oneDriveUploadUrl, HttpMethod.PUT, requestEntity, String.class);
 
        if (response.getStatusCode() == HttpStatus.CREATED) {
            //解析返回的JSON字符串,獲取文件路徑
            String downloadUrl = JSONObject.parseObject(response.getBody()).getString("@microsoft.graph.downloadUrl");
            storeFileInfoToExcel(fileName, downloadUrl);
            logger.info("文件上傳成功,OneDrive 文件路徑:" + downloadUrl);
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.setContentType("text/html;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            out.print("<script> alert('" + fileName + "已上傳成功!');window.location.href='file_info.xlsx';</script>");
        } else {
            throw new RuntimeException("文件上傳失?。?);
        }
    }
 
    /**
     * 將文件信息存儲(chǔ)到Excel文件中
     *
     * @param filename 文件名稱(chēng)
     * @param filepath 文件路徑
     */
    private void storeFileInfoToExcel(String filename, String filepath) {
        try {
            File file = new File(ResourceUtils.getURL("classpath:").getPath() + "/static/file_info.xlsx");
 
            XSSFWorkbook excel;
            XSSFSheet sheet;
            FileOutputStream out;
 
            // 如果文件存在,則讀取已有數(shù)據(jù)
            if (file.exists()) {
                FileInputStream fis = new FileInputStream(file);
                excel = new XSSFWorkbook(fis);
                sheet = excel.getSheetAt(0);
                fis.close();
            } else {
                // 如果文件不存在,則創(chuàng)建一個(gè)新的工作簿和工作表
                excel = new XSSFWorkbook();
                sheet = excel.createSheet("file_info");
                // 創(chuàng)建表頭
                XSSFRow headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("文件名稱(chēng)");
                headerRow.createCell(1).setCellValue("文件路徑");
            }
 
            // 獲取下一個(gè)行號(hào)
            int rowNum = sheet.getLastRowNum() + 1;
            // 創(chuàng)建新行
            XSSFRow newRow = sheet.createRow(rowNum);
            newRow.createCell(0).setCellValue(filename);
            newRow.createCell(1).setCellValue(filepath);
 
            // 將數(shù)據(jù)寫(xiě)入到文件
            out = new FileOutputStream(file);
            excel.write(out);
 
            // 關(guān)閉資源
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

4.編寫(xiě)認(rèn)證回調(diào)接口類(lèi)

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class RedirectController {
 
    /**
     * 回調(diào)地址
     * http://localhost:8080/redirectUri?code=M.C105_BL2.2.127d6530-7077-3bcd-081e-49be3abc3b45
     *
     * @param code
     * @return
     */
    @GetMapping("/redirectUri")
    public String redirectUri(String code) {
        return code;
    }
}

5.編寫(xiě)application.properties配置文件

# 應(yīng)用服務(wù) WEB 訪問(wèn)端口
server.port=8080
#OneDrive的ACCESS_TOKEN
onedrive.access-token=你的ACCESS_TOKEN

6.編寫(xiě)啟動(dòng)類(lèi)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class OneDriveUploadApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(OneDriveUploadApplication.class, args);
    }
 
}

7.編寫(xiě)上傳頁(yè)面,放在resources的static目錄中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上傳</title>
</head>
<body>
<div align="center">
    <h1>文件上傳</h1>
    <form action="upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file"><br><br>
        <input type="submit" value="提交">
    </form>
</div>
</body>
</html>

8.啟動(dòng)項(xiàng)目,訪問(wèn)http://localhost:8080/進(jìn)行測(cè)試

到此這篇關(guān)于SpringBoot實(shí)現(xiàn)OneDrive文件上傳的詳細(xì)步驟的文章就介紹到這了,更多相關(guān)SpringBoot OneDrive文件上傳內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot排除自動(dòng)加載數(shù)據(jù)源方式

    SpringBoot排除自動(dòng)加載數(shù)據(jù)源方式

    這篇文章主要介紹了SpringBoot排除自動(dòng)加載數(shù)據(jù)源方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • 深入理解java final不可變性

    深入理解java final不可變性

    本文主要介紹了講講java final不可變性,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-08-08
  • Java中的CompletableFuture原理與用法

    Java中的CompletableFuture原理與用法

    CompletableFuture 是由Java8引入的,這讓我們編寫(xiě)清晰可讀的異步代碼變得更加容易,該類(lèi)功能比Future 更加強(qiáng)大,在Java中CompletableFuture用于異步編程,異步通常意味著非阻塞,運(yùn)行任務(wù)單獨(dú)的線程,與主線程隔離,這篇文章介紹CompletableFuture原理與用法,一起看看吧
    2024-01-01
  • Java并發(fā)編程之Java內(nèi)存模型

    Java并發(fā)編程之Java內(nèi)存模型

    這篇文章主要為大家介紹了Java內(nèi)存模型,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助,希望能夠給你帶來(lái)幫助
    2021-11-11
  • java IO實(shí)現(xiàn)電腦搜索、刪除功能的實(shí)例

    java IO實(shí)現(xiàn)電腦搜索、刪除功能的實(shí)例

    下面小編就為大家?guī)?lái)一篇java IO實(shí)現(xiàn)電腦搜索、刪除功能的實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-12-12
  • Spring?Security的應(yīng)用案例講解

    Spring?Security的應(yīng)用案例講解

    Spring?Security支持多認(rèn)證方式(如OAuth2、JWT),實(shí)現(xiàn)基于角色的授權(quán)與防護(hù)(CSRF、會(huì)話管理),無(wú)縫集成Spring生態(tài),適用于構(gòu)建微服務(wù)安全體系,本文給大家介紹Spring?Security的基本使用示例,感興趣的朋友跟隨小編一起看看吧
    2025-09-09
  • 在Java中實(shí)現(xiàn)CQRS架構(gòu)的全過(guò)程

    在Java中實(shí)現(xiàn)CQRS架構(gòu)的全過(guò)程

    CQRS是Command?Query?Responsibility?Segregation的縮寫(xiě),一般稱(chēng)作命令查詢職責(zé)分離,本文給大家介紹在Java中實(shí)現(xiàn)CQRS架構(gòu)的全過(guò)程,感興趣的朋友跟隨小編一起看看吧
    2026-03-03
  • Java服務(wù)如何調(diào)用系統(tǒng)指令、Bat腳本記錄

    Java服務(wù)如何調(diào)用系統(tǒng)指令、Bat腳本記錄

    這篇文章主要介紹了Java服務(wù)如何調(diào)用系統(tǒng)指令、Bat腳本記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 使用IDEA搭建一個(gè)簡(jiǎn)單的SpringBoot項(xiàng)目超詳細(xì)過(guò)程

    使用IDEA搭建一個(gè)簡(jiǎn)單的SpringBoot項(xiàng)目超詳細(xì)過(guò)程

    這篇文章主要介紹了使用IDEA搭建一個(gè)簡(jiǎn)單的SpringBoot項(xiàng)目超詳細(xì)過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-02-02
  • ??Spring Boot SPI 用法教程?

    ??Spring Boot SPI 用法教程?

    文章介紹了Java SPI(服務(wù)提供者接口)和Spring Boot中的SPI機(jī)制,包括它們的定義、使用方式和實(shí)戰(zhàn)示例,文章還討論了常見(jiàn)問(wèn)題和最佳實(shí)踐,如版本兼容性、條件裝配、避免類(lèi)路徑?jīng)_突以及擴(kuò)展點(diǎn)選擇,感興趣的朋友一起看看吧
    2025-11-11

最新評(píng)論

钦州市| 额济纳旗| 阜阳市| 上栗县| 延津县| 阿克苏市| 肃北| 白玉县| 象州县| 景洪市| 凤庆县| 松潘县| 托克逊县| 大竹县| 即墨市| 水富县| 友谊县| 台南市| 舟曲县| 罗源县| 民乐县| 陆良县| 桐乡市| 金塔县| 太和县| 曲阜市| 杭锦旗| 安泽县| 连云港市| 崇左市| 开远市| 永福县| 赫章县| 柳江县| 安顺市| 阿坝县| 乐平市| 漠河县| 开原市| 萨嘎县| 利津县|