小程序上傳多張圖片到springboot后臺(tái),返回可供訪問(wèn)的圖片鏈接
最近在做小程序多圖片上傳到Java后臺(tái),Java后臺(tái)是用springboot寫(xiě)的。也算是踩了不少坑,今天就來(lái)帶大家來(lái)一步步實(shí)現(xiàn)小程序端多圖片的上傳。
首先看效果實(shí)現(xiàn)圖
小程序端上傳成功的回調(diào)

Java端接受到圖片后的打印

鏈接可以直接在瀏覽器里打開(kāi)查看
其實(shí)這兩個(gè)截圖就可以看出,我們圖片上傳成功了,并且給小程序前端返回了可供訪問(wèn)的圖片url。
話不多說(shuō),直接看代碼。
一,小程序端代碼
1,wxml布局文件

其實(shí)頁(yè)面很簡(jiǎn)答,一個(gè)上傳按鈕,一個(gè)選擇圖片按鈕。一定要記得先選擇圖片,然后再點(diǎn)擊圖片上傳。
2,js文件
再來(lái)看下js文件,js文件里最重要的就是uploadFile方法

uploadFile方法里我們請(qǐng)求自己的Java后臺(tái)接口,進(jìn)行圖片上傳。這里有些注意點(diǎn)要給大家說(shuō)下
小程序每次只能上傳單張圖片
如果采用for循環(huán)進(jìn)行上傳請(qǐng)求 會(huì)出現(xiàn)并行上傳,并行上傳會(huì)出現(xiàn)某一個(gè)圖片漏傳的問(wèn)題
我采用串行的思路,每張圖片執(zhí)行一次上傳請(qǐng)求,請(qǐng)求響應(yīng)成功后在調(diào)用請(qǐng)求上傳第二張圖片,以此類(lèi)推 。
下面把完整的代碼貼出來(lái)給到大家
Page({ ?data: { ? ?img_arr: [], ? ?formdata: '',
?}, ?//點(diǎn)擊發(fā)布按鈕
?formSubmit() { ? ?this.uploadFile(0)
?}, ?//上傳圖片
?uploadFile: function (index) { ? ?var that = this
? ?//如果所有圖片都已經(jīng)上傳完,就不再往下執(zhí)行
? ?if (index >= that.data.img_arr.length) { ? ? ?return
? ?}
? ?wx.uploadFile({ ? ? ?url: 'http://localhost:8080/upload/picture', //自己的Java后臺(tái)接口地址
? ? ?filePath: that.data.img_arr[index], ? ? ?name: 'content', ? ? ?header: { ? ? ? ?"Content-Type": "multipart/form-data", ? ? ? ?'accept': 'application/json', ? ? ? ?'Authorization': 'okgoodit' //若有token,此處換上你的token,沒(méi)有的話省略
? ? ?}, ? ? ?formData: ({ //上傳圖片所要攜帶的參數(shù)
? ? ? ?username: "編程小石頭", ? ? ? ?password: '2501902696'
? ? ?}), ? ? ?success: function (res) { ? ? ? ?console.log(`第${index+1}張上傳成功`, res)
? ? ? ?index++
? ? ? ?that.uploadFile(index)
? ? ?},
? ? ?fail(res) { ? ? ? ?console.log(`第${index+1}張上傳失敗`, res)
? ? ?}
? ?})
?}, ?//選擇要上傳的圖片
?upimg: function () { ? ?var that = this; ? ?//這里小程序規(guī)定最好只能選9張,我這里隨便填的3,你也可以自己改
? ?if (this.data.img_arr.length < 3) {
? ? ?wx.chooseImage({ ? ? ? ?sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認(rèn)二者都有
? ? ? ?sourceType: ['album', 'camera'], // 可以指定來(lái)源是相冊(cè)還是相機(jī),默認(rèn)二者都有
? ? ? ?success: function (res) {
? ? ? ? ?that.setData({ ? ? ? ? ? ?img_arr: that.data.img_arr.concat(res.tempFilePaths)
? ? ? ? ?});
? ? ? ?}
? ? ?})
? ?} else {
? ? ?wx.showToast({ ? ? ? ?title: '最多上傳三張圖片', ? ? ? ?icon: 'loading', ? ? ? ?duration: 3000
? ? ?});
? ?}
?},
})
代碼里注釋很清楚了。到這里小程序端基本上完事了。接下來(lái)我們看Java后臺(tái)的實(shí)現(xiàn)。
二,Java后臺(tái)代碼
先來(lái)看后臺(tái)代碼目錄,后臺(tái)代碼很簡(jiǎn)單,就是一個(gè)UploadController

這里的主要實(shí)現(xiàn)方法都在uploadPicture
@RequestMapping("/picture")
? ?public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception { ? ? ? ?String filePath = "";
? ? ? ?request.setCharacterEncoding("utf-8"); //設(shè)置編碼
? ? ? ?String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
? ? ? ?File dir = new File(realPath); ? ? ? ?//文件目錄不存在,就創(chuàng)建一個(gè)
? ? ? ?if (!dir.isDirectory()) {
? ? ? ? ? ?dir.mkdirs();
? ? ? ?} ? ? ? ?try {
? ? ? ? ? ?StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; ? ? ? ? ? ?//獲取formdata的值
? ? ? ? ? ?Iterator<String> iterator = req.getFileNames(); ? ? ? ? ? ?String username = request.getParameter("username"); ? ? ? ? ? ?String password = request.getParameter("password"); ? ? ? ? ? ?String timedata = request.getParameter("timedata"); ? ? ? ? ? ?while (iterator.hasNext()) {
? ? ? ? ? ? ? ?MultipartFile file = req.getFile(iterator.next()); ? ? ? ? ? ? ? ?String fileName = file.getOriginalFilename(); ? ? ? ? ? ? ? ?//真正寫(xiě)到磁盤(pán)上
? ? ? ? ? ? ? ?String uuid = UUID.randomUUID().toString().replace("-", ""); ? ? ? ? ? ? ? ?String kzm = fileName.substring(fileName.lastIndexOf(".")); ? ? ? ? ? ? ? ?String filename = uuid + kzm;
? ? ? ? ? ? ? ?File file1 = new File(realPath + filename);
? ? ? ? ? ? ? ?OutputStream out = new FileOutputStream(file1);
? ? ? ? ? ? ? ?out.write(file.getBytes());
? ? ? ? ? ? ? ?out.close();
? ? ? ? ? ? ? ?filePath = request.getScheme() + "://" +
? ? ? ? ? ? ? ? ? ? ? ?request.getServerName() + ":"
? ? ? ? ? ? ? ? ? ? ? ?+ request.getServerPort()
? ? ? ? ? ? ? ? ? ? ? ?+ "/uploadFile/" + filename;
? ? ? ? ? ? ? ?System.out.println("訪問(wèn)圖片路徑:" + filePath + "====username:" + username);
? ? ? ? ? ?}
? ? ? ?} catch (Exception e) {
? ? ? ? ? ?logger.error("", e);
? ? ? ?} ? ? ? ?return filePath;
? ?}
這里我給大家講下實(shí)現(xiàn)步驟
1,springboot對(duì)外提供接口供小程序訪問(wèn)
2,小程序上傳單個(gè)圖片和額外參數(shù)給后臺(tái)
3,后臺(tái)把圖片寫(xiě)到本地,或者圖片服務(wù)器,然后返回對(duì)應(yīng)的圖片url給到小程序端。

通過(guò)上圖可以看出,Java后臺(tái)返回了對(duì)應(yīng)的圖片url給前端,并且可以拿到小程序前端傳的用戶名。
我這里把完整的代碼貼給大家。
package com.img.demo;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStream;import java.util.Iterator;import java.util.UUID;/**
* 圖片上傳
* 編程小石頭
*/@RestController
@RequestMapping("/upload")
public class UploadController {
? ?private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
? ?@RequestMapping("/picture")
? ?public String uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception { ? ? ? ?String filePath = "";
? ? ? ?request.setCharacterEncoding("utf-8"); //設(shè)置編碼
? ? ? ?String realPath = request.getSession().getServletContext().getRealPath("/uploadFile/");
? ? ? ?File dir = new File(realPath); ? ? ? ?//文件目錄不存在,就創(chuàng)建一個(gè)
? ? ? ?if (!dir.isDirectory()) {
? ? ? ? ? ?dir.mkdirs();
? ? ? ?} ? ? ? ?try {
? ? ? ? ? ?StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request; ? ? ? ? ? ?//獲取formdata的值
? ? ? ? ? ?Iterator<String> iterator = req.getFileNames(); ? ? ? ? ? ?String username = request.getParameter("username"); ? ? ? ? ? ?String password = request.getParameter("password"); ? ? ? ? ? ?String timedata = request.getParameter("timedata"); ? ? ? ? ? ?while (iterator.hasNext()) {
? ? ? ? ? ? ? ?MultipartFile file = req.getFile(iterator.next()); ? ? ? ? ? ? ? ?String fileName = file.getOriginalFilename(); ? ? ? ? ? ? ? ?//真正寫(xiě)到磁盤(pán)上
? ? ? ? ? ? ? ?String uuid = UUID.randomUUID().toString().replace("-", ""); ? ? ? ? ? ? ? ?String kzm = fileName.substring(fileName.lastIndexOf(".")); ? ? ? ? ? ? ? ?String filename = uuid + kzm;
? ? ? ? ? ? ? ?File file1 = new File(realPath + filename);
? ? ? ? ? ? ? ?OutputStream out = new FileOutputStream(file1);
? ? ? ? ? ? ? ?out.write(file.getBytes());
? ? ? ? ? ? ? ?out.close();
? ? ? ? ? ? ? ?filePath = request.getScheme() + "://" +
? ? ? ? ? ? ? ? ? ? ? ?request.getServerName() + ":"
? ? ? ? ? ? ? ? ? ? ? ?+ request.getServerPort()
? ? ? ? ? ? ? ? ? ? ? ?+ "/uploadFile/" + filename;
? ? ? ? ? ? ? ?System.out.println("訪問(wèn)圖片路徑:" + filePath + "====username:" + username);
? ? ? ? ? ?}
? ? ? ?} catch (Exception e) {
? ? ? ? ? ?logger.error("", e);
? ? ? ?} ? ? ? ?return filePath;
? ?}
}
至于如何創(chuàng)建springboot項(xiàng)目這么基礎(chǔ)的知識(shí),我這里就不再給大家講解了。
到這里,我們的小程序多圖片上傳就算大工告成了,后面我會(huì)錄制相關(guān)的視頻出來(lái),感興趣的同學(xué)可以關(guān)注“編程小石頭”公眾號(hào),回復(fù)“多圖片上傳”,即可獲取源碼。
