java SSM上傳圖片到後端(再傳到七牛雲)教程以及出現的各種異常解決辦法

異常一:Error creating bean with name 'multipartResolver': Failed to introspect bean class 

解決辦法:在pom.xml添加依賴

<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.1</version>
</dependency>

異常二:MissingServletRequestParameterException:Required: CommonsMultipartFile parameter 'file' is not present

在SpringMVC-Servlet.xml裏面增加一個bean字段

<bean id="multipartResolver"
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 設置上傳文件的最大尺寸爲10MB 10*1024*1024 -->
   <property name="maxUploadSize">
      <value>10485760</value>
   </property>
</bean>

控制器的方法裏要加上@RequestParam(Value="") 

public String upload(@RequestParam(value = "file",required = false) CommonsMultipartFile file, HttpSession session)

接着提供七牛雲的工具類:

package com.zy.ninepalaceappapi.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;

public class QiniuUploadImageUtil {
    //accessKey
    private static String accessKey = "████████████████████████████████████";//用鑰匙 刮 屏幕得字符串
    //secretKey
    private static String secretKey ="██████████████████████████████████████████";
    //儲存空間名
    private static String bucket ="██████████████████████████████████████████";
    //外鏈URL前綴
    private static String fronturl = "████████████████████████████████████";


    /**
     * 圖片上傳

     * @param file  圖片路徑
     * @return  鏈接
     * @throws QiniuException
     */
    public static  String  fileUpload(String file)throws QiniuException {
        Auth auth = Auth.create(accessKey,secretKey);
        String upToken = auth.uploadToken(bucket);  //上傳憑證
        Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new UploadManager(cfg);
        String key  = null;
        try {
            Response response = uploadManager.put(file, key, upToken);
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(),DefaultPutRet.class);
            return fronturl+putRet.key;
        }catch (QiniuException ex){
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                // ignore
            }
        }
        return null;
    }

    /**
     *刪除圖片
     * @param key
     * @return
     * @throws QiniuException
     */
    public static String delete(String key)throws QiniuException{
        Auth auth = Auth.create(accessKey,secretKey);
        Configuration cfg = new Configuration(Zone.zone2());
        BucketManager bucketMgr = new BucketManager(auth, cfg);
        try {
            bucketMgr.delete(bucket,key);
        }catch (QiniuException Q){
            return Q.toString();
        }
        System.out.println("success");
        return null;
    }











}

接着控制器的方法:

步驟:

1.由於七牛雲工具類的方法是獲取圖片的本地路徑,所以需要一箇中轉,因此請求參數是MultipartFile類型

2.從前端拿到file對象後先臨時儲存到項目本地再獲取路徑

3.調用七牛工具類的上傳圖片方法傳入圖片路徑

4.最後上傳完了就刪除本地的那張圖片

@ResponseBody
@RequestMapping("uploadImage")
public String upload(@RequestParam(value = "file",required = false) CommonsMultipartFile file, HttpSession session)throws QiniuException{
    try {
        String path = session.getServletContext().getRealPath("/")+file.getOriginalFilename();
        System.out.println(path);
        file.transferTo(new File(path));
        String url =QiniuUploadImageUtil.fileUpload(path);
        File f = new File(path);
        f.delete();
        return url;
    }catch (Exception e){
        return e.toString();
    }
}

最後寫 一個前端html來上傳圖片:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input type="file" onchange="aaa()" name="">
	<img src="https://afp.alicdn.com/afp-creative/creative/u124884735/55308755880f8b637dde1f88b84ea9da.png" onclick="ButtonClick(this)">
	<script type="text/javascript">
		function aaa(e) {
			let a = document.getElementsByTagName('input')[0].files[0]
			let b = document.getElementsByTagName('input')[0].value
			let c = new FormData()
			c.append('file',a)
			let ajax = new XMLHttpRequest()
			ajax.open('POST','http://192.168.0.119:8080/shop/uploadImage',true)
			ajax.send(c)
		}

		function ButtonClick(div) 
		{ 
		// var div = document.getElementById('divId'); 
		div.contentEditable = 'true'; 
		var controlRange; 
		if (document.body.createControlRange) { 
		controlRange = document.body.createControlRange(); 
		controlRange.addElement(div); 
		controlRange.execCommand('Copy'); 
		} 
		div.contentEditable = 'false'; 
		} 
	</script>
</body>
</html>

最後測試。

上傳圖片,返回了一個URL




打開鏈接:



最後附上七牛雲的依賴(我也是拷過來的):

<dependency>
 <groupId>com.qiniu</groupId>
 <artifactId>qiniu-java-sdk</artifactId>
 <version>7.2.6</version>
 <scope>compile</scope>
</dependency>
<dependency>
 <groupId>com.squareup.okhttp3</groupId>
 <artifactId>okhttp</artifactId>
 <version>3.3.1</version>
 <scope>compile</scope>
</dependency>
<dependency>
 <groupId>com.google.code.gson</groupId>
 <artifactId>gson</artifactId>
 <version>2.6.2</version>
 <scope>compile</scope>
</dependency>
<dependency>
 <groupId>com.qiniu</groupId>
 <artifactId>happy-dns-java</artifactId>
 <version>0.1.4</version>
 <scope>compile</scope>
</dependency>



異常部分參考教程文章 :點擊打開鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章