微信小程序选择图片、预览图片、长按删除图片(请求后端同时删除文件)以及上传图片。
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"; } }