微信小程序選擇圖片、預覽圖片、長按刪除圖片(請求後端同時刪除文件)以及上傳圖片。
js
const app = getApp()
var filePath = ''
// component/uploadImages/index.js
Component({
/**
* 組件的屬性列表
*/
properties: {
count: { //最多選擇圖片的張數,默認4張
type: Number,
value: 4
},
uploadUrl: { //圖片上傳的服務器路徑
type: String,
value: 'http://192.168.2.139:8012/upload/file'
},
showUrl: { //圖片的拼接路徑
type: String,
value: 'http://192.168.2.139:8099/'
},
deleteUrl: { //圖片刪除的服務器路徑
type: String,
value: 'http://192.168.2.139:8012/upload/deleteFile'
},
},
/**
* 組件的初始數據
*/
data: {
detailPics: [], //上傳的結果圖片集合
url:'/upload/file'
},
ready: function() {
console.log(this.data)
},
/**
* 組件的方法列表
*/
methods: {
uploadDetailImage: function(e) { //這裏是選取圖片的方法
var that = this;
var pics = [];
var detailPics = that.data.detailPics;
if (detailPics.length >= that.data.count) {
wx.showToast({
title: '最多選擇' + that.data.count + '張!',
})
return;
}
wx.chooseImage({
count: that.data.count, // 最多可以選擇的圖片張數,默認9
sizeType: ['original', 'compressed'], // original 原圖,compressed 壓縮圖,默認二者都有
sourceType: ['album', 'camera'], // album 從相冊選圖,camera 使用相機,默認二者都有
success: function(res) {
var imgs = res.tempFilePaths;
for (var i = 0; i < imgs.length; i++) {
pics.push(imgs[i])
}
that.uploadimg({
url: that.data.uploadUrl, //這裏是你圖片上傳的接口
path: pics, //這裏是選取的圖片的地址數組
});
},
})
},
//多張圖片上傳
uploadimg: function(data) {
console.log(data)
wx.showLoading({
title: '上傳中...',
mask: true,
})
var that = this,
i = data.i ? data.i : 0,
success = data.success ? data.success : 0,
fail = data.fail ? data.fail : 0;
wx.uploadFile({
url: data.url,
filePath: data.path[i],
name: 'file',
formData: {'manageCode': app.globalData.manageCode},
success: (resp) => {
wx.hideLoading();
success++;
var str = resp.data //返回的結果,可能不同項目結果不一樣
var pic_name = that.data.showUrl + str;
var detailPics = that.data.detailPics;
pic_name = pic_name.replace(/\\/g , '/');
console.log(filePath);
detailPics.push(pic_name);
that.setData({
detailPics: detailPics
})
},
fail: (res) => {
fail++;
console.log('fail:' + i + "fail:" + fail);
},
complete: () => {
i++;
if (i == data.path.length) { //當圖片傳完時,停止調用
console.log('執行完畢');
console.log('成功:' + success + " 失敗:" + fail);
var myEventDetail = {
picsList: that.data.detailPics
} // detail對象,提供給事件監聽函數
var myEventOption = {} // 觸發事件的選項
that.triggerEvent('myevent', myEventDetail, myEventOption)//結果返回調用的頁面
} else { //若圖片還沒有傳完,則繼續調用函數
data.i = i;
data.success = success;
data.fail = fail;
that.uploadimg(data);//遞歸,回調自己
}
}
});
},
/**長按刪除 */
bindlongpressimg(e){
let that = this
var deleID = e.currentTarget.dataset.id //獲取點擊項目的內容
var detailPics = that.data.detailPics;
console.log(deleID)
console.log(detailPics)
console.log(e)
wx.showModal({
title: '提示',
content: '確定要刪除此圖片嗎?',
success: function (res) {
if (res.confirm) {
console.log('點擊確定了');
detailPics.splice(deleID,1)
} else if (res.cancel) {
console.log('點擊取消了');
return false;
}
that.setData({
detailPics:detailPics
})
}
})
var target_url = detailPics[deleID];
//後臺刪除
wx.request({
url: that.data.deleteUrl,
method: "POST",
data: {
filePath: target_url
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: (res) => {
// console.log(res.data);
console.log(res);
}
})
},
previewImage: function (e) {//預覽圖片
var that = this;
console.log(e);
var deleID = e.currentTarget.dataset.id //獲取點擊項目的內容
var detailPics = that.data.detailPics;
console.log(deleID)
console.log(detailPics)
wx.previewImage({
current: deleID, // 當前顯示圖片的http鏈接
urls: that.data.detailPics // 需要預覽的圖片http鏈接列表
})
},
}
})
wxml
<view class='content'>
<view class='img-box'>
<view class='img-list'>
<block wx:for="{{detailPics}}" wx:key="index">
<view class='img-item'>
<image src='{{item}}' bindtap='previewImage' bindlongpress="bindlongpressimg" data-id='{{index}}'></image>
</view>
</block>
<view class='chooseimg' bindtap='uploadDetailImage'>
<view class="weui-uploader__input-box"></view>
</view>
</view>
<view class='tips'>長按對應的圖片即可刪除</view>
<uploadImages bindmyevent="myEventListener" count='{{countPic}}' showUrl="{{showImgUrl}}" uploadUrl="{{uploadImgUrl}}"></uploadImages>
</view>
</view>
wxss
.content {
width: 100%;
background-color: #fff;
}
.img-list {
display: flex;
display: -webkit-flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
flex-wrap: wrap;
}
.img-item {
width: 30%;
text-align: left;
margin-right: 20rpx;
margin-bottom: 10rpx;
}
.img-item image {
width: 180rpx;
height: 180rpx;
}
.submit-btn {
width: 100%;
background-color: #fff;
height: 80rpx;
text-align: center;
line-height: 80rpx;
font-size: 30rpx;
position: fixed;
bottom: 100rpx;
}
.chooseimg {
background-color: #fff;
}
.weui-uploader__input-box {
float: left;
position: relative;
margin-right: 9px;
margin-bottom: 9px;
width: 180rpx;
height: 180rpx;
border: 1px solid #d9d9d9;
}
.weui-uploader__input-box:before {
width: 2px;
height: 39.5px;
}
.weui-uploader__input-box:after, .weui-uploader__input-box:before {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #d9d9d9;
}
.weui-uploader__input-box:after {
width: 39.5px;
height: 2px;
}
.weui-uploader__input-box:after, .weui-uploader__input-box:before {
content: " ";
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
background-color: #d9d9d9;
}
.tips {
color: #666;
font-size: 24rpx;
padding-bottom: 20rpx;
}
.img-box {
width: 92%;
margin: auto;
padding-top: 20rpx;
}
java 後臺
package com.tenru.rest.controller;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.tenru.rest.utils.CommonTools;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
@RestController
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/result")
public String result() {
return "result";
}
@PostMapping("/file")
public String singleFileUpload(@RequestParam("file") MultipartFile file, String manageCode, RedirectAttributes redirectAttributes, HttpServletRequest request) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:result";
}
if (StringUtils.isEmpty(manageCode)){
redirectAttributes.addFlashAttribute("message", "manage_code 不能爲空");
return "error";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadDirectory(manageCode) + "/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", file.getOriginalFilename() + " upload success");
String filePath = path.toString();
filePath = filePath.substring(filePath.indexOf("upload\\") );
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/result";
}
private String uploadDirectory(String manage_code) throws FileNotFoundException {
// 獲取根目錄
File path = new File(ResourceUtils.getURL("classpath:").getPath());
if (!path.exists())
path = new File("");
System.out.println("path:" + path.getAbsolutePath());
// 如果上傳目錄爲/static/images/upload/,則可以如下獲取:
String timeFormat = CommonTools.getTimeFormat();
timeFormat = manage_code + "_" + timeFormat;
String childPath = "static/upload/" + timeFormat + "/";
File upload = new File(path.getAbsolutePath(), childPath);
if (!upload.exists())
upload.mkdirs();
System.out.println("upload url:" + upload.getAbsolutePath());
// 在開發測試模式時,得到的地址爲:{項目跟目錄}/target/static/images/upload/
// 在打包成jar正式發佈時,得到的地址爲:{發佈jar包目錄}/static/images/upload/
return upload.getAbsolutePath();
}
@PostMapping("/deleteFile")
public String deleteFile(String filePath,RedirectAttributes redirectAttributes) throws FileNotFoundException {
if (filePath.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:result";
}
int index = filePath.indexOf("upload");
filePath = filePath.substring(index);
// 獲取根目錄
File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
// 組裝 文件
String path = rootPath.getAbsolutePath() + "\\static\\" + filePath;
File targetFile = new File(path);
if (targetFile.exists()){
targetFile.delete();
}else{
//
}
return "redirect:/result";
}
}