java后台簡單從阿里雲上傳下載文件並通知前端以附件的形式保存


 

一、 首先開通阿里的OSS 服務 創建一個存儲空間在新建一個Bucket 在你新建的bucket有所需的id和key

獲取外網訪問地址或者是內網 看個人需求 我使用的是外網(內網沒用過 估計是部署到阿里雲服務器可以使用內網) 獲取endpoint

 

 

 好了前期准備工作完事

 以下是我項目的機構

 

  pom 配置

<?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>xudy.top</groupId>
    <artifactId>OssAction</artifactId>
    <version>1.0-SNAPSHOT</version>



    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.7.0</version>
        </dependency>

    </dependencies>

</project>

 

 

 ConfigUtols 配置代碼

@Component
public class ConfigUtils {


    /**
     *  騰訊雲配置
     * @return
     */
    @Bean
    public OSSClient getCOSClient() {
        return this.getOSSClient();
    }





        /**
         * 阿里雲OSS對象存儲 客戶端
         * @return
         */
        public static OSSClient getOSSClient() {
            String endpoint         = "http://os.com";
            String accessKeyId      = "LTadAI";
            String accessKeySecret  = "zLIRj001";
            // 創建OSSClient實例
            OSSClient ossClient     = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            return ossClient;
        }




}

 

Controller  里包含 上傳 和下載代碼:

 
         
@RestController
public class MainController {

@Autowired
OSSClient ossClient;

@GetMapping(value = "/upload")
public String OSSUpLoad(){

// 上傳byte數組
// byte[] content = "Hello OSS xudy".getBytes();
// ossClient.putObject("xudy", "xudy", new ByteArrayInputStream(content));

String filePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + "top.jpg";
// 上傳文件流
try {
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);

// 上傳文件
ossClient.putObject("xudy", "txt.jpg", inputStream);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("上傳阿里雲OSS服務器異常." + e.getMessage());

}
// 關閉client 正常開發的時候 做好把下面代碼屏蔽
// ossClient.shutdown();

return "upload";
}

@GetMapping(value = "/download")
public void OssAction(HttpServletRequest request, HttpServletResponse response){
try {
String fileName="txt.jpg";
String ossKey="txt.jpg";
// 從阿里雲進行下載
OSSObject ossObject = ossClient.getObject("xudy",ossKey);//bucketName需要自己設置
// 已緩沖的方式從字符輸入流中讀取文本,緩沖各個字符,從而提供字符、數組和行的高效讀取
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));

InputStream inputStream = ossObject.getObjectContent();

//緩沖文件輸出流
BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
//通知瀏覽器以附件形式下載
// response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 為防止 文件名出現亂碼
response.setContentType("application/doc");
final String userAgent = request.getHeader("USER-AGENT");
if(StringUtils.contains(userAgent, "MSIE")){//IE瀏覽器
fileName = URLEncoder.encode(fileName,"UTF-8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐瀏覽器
fileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
fileName = URLEncoder.encode(fileName,"UTF-8");//其他瀏覽器
}
response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//這里設置一下讓瀏覽器彈出下載提示框,而不是直接在瀏覽器中打開


// 進行解碼 如果上傳時為了防止亂碼 進行解碼使用此方法
BASE64Decoder base64Decoder = new BASE64Decoder();
// byte[] car;
// while (true) {
// String line = reader.readLine();
// if (line == null) break;
// car = base64Decoder.decodeBuffer(line);
//
// outputStream.write(car);
// }
// reader.close();

byte[] car = new byte[1024];
int L;

while((L = inputStream.read(car)) != -1){
if (car.length!=0){
outputStream.write(car, 0,L);
}
}

if(outputStream!=null){
outputStream.flush();
outputStream.close();
}


} catch (IOException e) {
e.printStackTrace();

} catch (OSSException e){

}
}

/**
* 刪除存儲空間buckName
*/
public void deleteBucket(){
ossClient.deleteBucket("");

}
 

注意:在實際使用該方法下載的過程中,可能遇到服務器不報錯,但就是下載不下來文件的問題,這樣有可能是前端頁面發出下載請求的方式有誤,不能使用AJAX的get方式訪問該方法,因為Ajax能夠返回的數據格式只能為html,script,json,xml,不接受流的形式。筆者使用的方式是用window.location.href訪問,或者使用from表單提交方式(GET/POST)。

   源碼:git@gitee.com:xdymemory00/OssDownLoad.git

借鑒來源:https://www.alibabacloud.com/help/zh/doc-detail/32014.htm

 


免責聲明!

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



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