1. 程式人生 > >SpringMVC上傳圖片檔案到 騰訊雲【2018年最新版】【JavaWeb】

SpringMVC上傳圖片檔案到 騰訊雲【2018年最新版】【JavaWeb】

pom.xml

<properties>
    <spring.version>4.2.4.RELEASE</spring.version>
  </properties>
  <dependencies>
    <!--Spring-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--Jsp-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
    </dependency>
    <!--騰訊雲-->
    <dependency>
      <groupId>com.qcloud</groupId>
      <artifactId>cos_api</artifactId>
      <version>5.2.4</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.5.1</version>
    </dependency>
    <!-- 檔案上傳所依賴的jar包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
  </dependencies>

COSClientUtil.java

package com.neusoft.util;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;

/**
 * @author XiaoLuo
 * @ClassName: com.neusoft.controller.util.COSClientUtil
 * @Description: ${todo}
 * @date 2018/3/12 15:37
 */
public class COSClientUtil {

	//todo 這些變數資訊自行到 騰訊雲物件儲存控制檯 獲取
	// 儲存通名稱			替換成自己的
	private static final String bucketName = "storage-1254279902";
	//secretId 			替換成自己的
	private static final String secretId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
	// secretKey		        替換成自己的
	private static final String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";

	// 1 初始化使用者身份資訊(secretId, secretKey)
	private static final COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
	// 2 設定bucket的區域, COS地域的簡稱請參照 https://cloud.tencent.com/document/product/436/6224
	private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
	// 3 生成cos客戶端
	private static final COSClient cosClient = new COSClient(cred, clientConfig);
	// 檔案儲存目錄
	//private String filedir = "blog/";
	private COSClient cOSClient;

	public COSClientUtil() {
		cOSClient = new COSClient(cred, clientConfig);
	}

	/**
	 * 銷燬
	 */
	public void destory() {
		cOSClient.shutdown();
	}

	/**
	 * 上傳圖片
	 *
	 * @param url
	 */
	public void uploadImg2Cos(String url) throws Exception {
		File fileOnServer = new File(url);
		FileInputStream fin;
		try {
			fin = new FileInputStream(fileOnServer);
			String[] split = url.split("/");
			this.uploadFile2Cos(fin, split[split.length - 1]);
		} catch (FileNotFoundException e) {
			throw new Exception("圖片上傳失敗");
		}
	}

	public String uploadFile2Cos(MultipartFile file) throws Exception {
		if (file.getSize() > 10 * 1024 * 1024) {
			throw new Exception("上傳圖片大小不能超過10M!");
		}
		String originalFilename = file.getOriginalFilename();
		String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
		Random random = new Random();
		String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
		try {
			InputStream inputStream = file.getInputStream();
			this.uploadFile2Cos(inputStream, name);
			return name;
		} catch (Exception e) {
			throw new Exception("圖片上傳失敗");
		}
	}

	/**
	 * 獲得圖片路徑
	 *
	 * @param fileUrl
	 * @return
	 */
	public String getImgUrl(String fileUrl) {
		return getUrl(fileUrl);
	}

	/**
	 * 獲得url連結
	 *
	 * @param key
	 * @return
	 */
	public String getUrl(String key) {
		// 設定URL過期時間為10年 3600l* 1000*24*365*10
		Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
		// 生成URL
		URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
		if (url != null) {
			return url.toString();
		}
		return null;
	}

	/**
	 * 上傳到COS伺服器 如果同名檔案會覆蓋伺服器上的
	 *
	 * @param instream
	 *            檔案流
	 * @param fileName
	 *            檔名稱 包括字尾名
	 * @return 出錯返回"" ,唯一MD5數字簽名
	 */
	public String uploadFile2Cos(InputStream instream, String fileName) {
		String ret = "";
		try {
			// 建立上傳Object的Metadata
			ObjectMetadata objectMetadata = new ObjectMetadata();
			objectMetadata.setContentLength(instream.available());
			objectMetadata.setCacheControl("no-cache");
			objectMetadata.setHeader("Pragma", "no-cache");
			objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
			objectMetadata.setContentDisposition("inline;filename=" + fileName);
			// 上傳檔案
			PutObjectResult putResult = cOSClient.putObject(bucketName,  fileName, instream, objectMetadata);
			ret = putResult.getETag();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (instream != null) {
					instream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return ret;
	}

	/**
	 * Description: 判斷Cos服務檔案上傳時檔案的contentType
	 *
	 * @param filenameExtension 檔案字尾
	 * @return String
	 */
	public static String getcontentType(String filenameExtension) {
		if (filenameExtension.equalsIgnoreCase("bmp")) {
			return "image/bmp";
		}
		if (filenameExtension.equalsIgnoreCase("gif")) {
			return "image/gif";
		}
		if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
				|| filenameExtension.equalsIgnoreCase("png")) {
			return "image/jpeg";
		}
		if (filenameExtension.equalsIgnoreCase("html")) {
			return "text/html";
		}
		if (filenameExtension.equalsIgnoreCase("txt")) {
			return "text/plain";
		}
		if (filenameExtension.equalsIgnoreCase("vsd")) {
			return "application/vnd.visio";
		}
		if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
			return "application/msword";
		}
		if (filenameExtension.equalsIgnoreCase("xml")) {
			return "text/xml";
		}
		return "image/jpeg";
	}


}

UploadController.java

package com.neusoft.controller;

import com.neusoft.util.COSClientUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author XiaoLuo
 * @ClassName: UserController
 * @Description: ${todo}
 * @date 2017/9/1 17:57
 */
@Controller
public class UploadController {

	@RequestMapping("/")
	public ModelAndView index() {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("index");
		return modelAndView;
	}


	@RequestMapping("/upload")
	@ResponseBody
	public Object upload(@RequestParam("file") MultipartFile file)throws Exception{
		COSClientUtil cosClientUtil = new COSClientUtil();
		String name = cosClientUtil.uploadFile2Cos(file);
		String imgUrl = cosClientUtil.getImgUrl(name);
		String[] split = imgUrl.split("\\?");
		return split[0];
	}
}

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

<form id="uploadForm" enctype="multipart/form-data">
    <input id="file" type="file" name="file"/>
    <br><br><br>
    <button id="upload" type="button" onclick="uploadImg()" >測試上傳圖片到騰訊雲</button>
</form>
<script>
    /*
      ajax檔案上傳教程:
      https://blog.csdn.net/inuyasha1121/article/details/51915742
      */
    function uploadImg() {
        debugger
        $.ajax({
            type: "post",
            url: '/upload',
            data: new FormData($('#uploadForm')[0]),
            processData: false,
            contentType: false,
            success: function (data) {
                alert(data)
            },
            error:function (XMLHttpRequest, textStatus, errorThrown) {
                alert("請求失敗!");
            }
        });
    }
</script>
</body>
</html>
整個案例工程已上傳到CSDN,點選開啟連結