SpringBoot實現(xiàn)OneDrive文件上傳的詳細步驟
SpringBoot實現(xiàn)OneDrive文件上傳
源碼
OneDriveUpload: SpringBoot實現(xiàn)OneDrive文件上傳
獲取accessToken步驟
參考文檔:針對 OneDrive API 的 Microsoft 帳戶授權(quán) - OneDrive dev center | Microsoft Learn
1.訪問Azure創(chuàng)建應(yīng)用Microsoft Azure,使用微軟賬號進行登錄即可!


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

3.獲取code
通過訪問(必須用瀏覽器,通過地址欄輸入的方式):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


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

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

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

正常情況下訪問后就能得到access_token,然后把access_token放在springboot的配置文件中!
代碼實現(xiàn)步驟
1. 新建一個springBoot項目,選擇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.編寫文件上傳接口類
參考文檔:上傳小文件 - 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并將文件信息存儲到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("文件上傳失?。?);
}
}
/**
* 將文件信息存儲到Excel文件中
*
* @param filename 文件名稱
* @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)建一個新的工作簿和工作表
excel = new XSSFWorkbook();
sheet = excel.createSheet("file_info");
// 創(chuàng)建表頭
XSSFRow headerRow = sheet.createRow(0);
headerRow.createCell(0).setCellValue("文件名稱");
headerRow.createCell(1).setCellValue("文件路徑");
}
// 獲取下一個行號
int rowNum = sheet.getLastRowNum() + 1;
// 創(chuàng)建新行
XSSFRow newRow = sheet.createRow(rowNum);
newRow.createCell(0).setCellValue(filename);
newRow.createCell(1).setCellValue(filepath);
// 將數(shù)據(jù)寫入到文件
out = new FileOutputStream(file);
excel.write(out);
// 關(guān)閉資源
out.close();
excel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}4.編寫認證回調(diào)接口類
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.編寫application.properties配置文件
# 應(yīng)用服務(wù) WEB 訪問端口 server.port=8080 #OneDrive的ACCESS_TOKEN onedrive.access-token=你的ACCESS_TOKEN
6.編寫啟動類
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.編寫上傳頁面,放在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.啟動項目,訪問http://localhost:8080/進行測試
到此這篇關(guān)于SpringBoot實現(xiàn)OneDrive文件上傳的詳細步驟的文章就介紹到這了,更多相關(guān)SpringBoot OneDrive文件上傳內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot集成PDFBox實現(xiàn)電子簽章的代碼詳解
Apache PDFBox 是一個開源的 Java 庫,用于處理 PDF 文檔,它提供了一系列強大的功能,包括創(chuàng)建、渲染、拆分、合并、加密、解密 PDF 文件,以及從 PDF 中提取文本和元數(shù)據(jù)等,本文給大家介紹了SpringBoot集成PDFBox實現(xiàn)電子簽章,需要的朋友可以參考下2024-09-09
解決fastjson從1.1.41升級到1.2.28后報錯問題詳解
這篇文章主要介紹了解決fastjson從1.1.41升級到1.2.28后報錯問題詳解,需要的朋友可以參考下2020-02-02
SpringBoot整合RabbitMQ的5種模式實戰(zhàn)
本文主要介紹了SpringBoot整合RabbitMQ的5種模式實戰(zhàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
基于SpringMVC中的路徑參數(shù)和URL參數(shù)實例
這篇文章主要介紹了基于SpringMVC中的路徑參數(shù)和URL參數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
SpringBoot使用自動配置xxxAutoConfiguration
這篇文章介紹了SpringBoot自動配置xxxAutoConfiguration的使用方法,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
JAVA通過Filter實現(xiàn)允許服務(wù)跨域請求的方法
這里的域指的是這樣的一個概念:我們認為若協(xié)議 + 域名 + 端口號均相同,那么就是同域即我們常說的瀏覽器請求的同源策略。這篇文章主要介紹了JAVA通過Filter實現(xiàn)允許服務(wù)跨域請求,需要的朋友可以參考下2018-11-11

