前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >文件上传配合后端

文件上传配合后端

作者头像
Remember_Ray
发布2020-11-04 14:31:09
5180
发布2020-11-04 14:31:09
举报
文章被收录于专栏:Ray学习笔记Ray学习笔记

官方文档-wx.chooseMessageFile

小程序端

wxml

代码语言:javascript
复制
<form bindsubmit="formSubmit" bindreset="formReset">
    <view style='position: fixed; width: 100%;'>
        <view class='tu1'>
            <block wx:for="{{img_arr}}" wx:key="index">
                <view class='logoinfo'>
                    <image class='logoinfo' mode="aspectFill" src='{{item}}' data-index="{{index}}" bindtap="previewImg" bindlongpress="deleteImg" name="headimage"></image>
                </view>
            </block>
            <image bindtap='upimg' class='tu' src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1574928754865&di=a3371dc82dcca560ba08835cb98d707a&imgtype=0&src=http%3A%2F%2Fku.90sjimg.com%2Felement_origin_min_pic%2F00%2F92%2F66%2F7456f22e7ae8990.jpg"></image>
        </view>
        <view class='an1'>
            <button form-type="submit" class='an'>发布</button>
        </view>
    </view>
</form>

wxss

代码语言:javascript
复制
.tu {  
    /* border: 3rpx solid rgba(0, 0, 0, 0.329);  */
    border-radius: 10rpx;  
    height: 260rpx;  width: 260rpx;  
    margin: 5rpx 5rpx 5rpx 5rpx;   
}
.logoinfo { 
    height: 220rpx; 
    width: 220rpx; 
    margin: 10rpx 10rpx 10rpx 10rpx;
    }
.tu1 {  
    display: flex;  
    flex-flow: row wrap;  
    align-content: space-around;
}
.an {  
    height: 90rpx;  
    width: 270rpx;  
    font-size: 38rpx;  
    background-color: rgba(146, 163, 45, 0.288);  
    font-weight: 600;  
    color: white;
}
button::after {  
    border: none;
}
.an1 {  
    margin-top: 90rpx;
}

js

代码语言:javascript
复制
// miniprogram/components/action/action.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 图片数组
    img_arr: [],
    // 文件数组
    file_arr: []
  },


  /** 从本地获取照片  */
  upimg: function () {
    var that = this;
    // 最多上传9张图片
    if (this.data.img_arr.length < 9) {
      wx.chooseImage({
        count: 9,

        success(res) {
          console.log(res)
          const tempFilePaths = res.tempFilePaths[0]
          console.log(tempFilePaths)
          //concat() 方法用于连接两个或多个数组
          that.setData({
            img_arr: that.data.img_arr.concat(tempFilePaths)
          })
        }
      })
    } else {
      wx.showToast({
        title: '最多上传九张图片', //提示的内容,
        icon: 'loading', //图标,
        // duration: 2000, //延迟时间,
        mask: true, //显示透明蒙层,防止触摸穿透,
        success: res => { }
      });

    }
  },

  /** 删除照片功能与预览照片功能  */
  deleteImg: function (e) {
    var that = this;
    var img_arr = that.data.img_arr;
    var index = e.currentTarget.dataset.index;
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗?',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          img_arr.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          img_arr: img_arr
        });
      }
    })
  },

  /** 预览图片 */
  previewImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var img_arr = this.data.img_arr;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },

  /** 上传图片到服务器 */
  formSubmit: function () {
    var that = this
    var adds = that.data.img_arr
    for (var i = 0; i < this.data.img_arr.length; i++) {
      wx.uploadFile({
        url: 'http://127.0.0.1:8078/app/wx/upload/file',  //填写实际接口,仅测试   
        header: {
          "Content-Type": "multipart/form-data"
        },
        filePath: that.data.img_arr[i],
        name: 'content',
        formData: {
          'adds': adds
        },
        success: function (res) {
          console.log(res)
          if (res) {
            wx.showToast({
              title: '已提交发布!',
              duration: 3000
            });
          }
        }
      })
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }

})

界面

初始界面

上传图片

预览图片

点击图片

删除图片

长按图片

发布图片

Java 端

properties

代码语言:javascript
复制
miniapp_file_path=F:/uploads/

controller

代码语言:javascript
复制
package com.dfht.modules.miniapp.controller;

import com.dfht.common.utils.StringUtils;
import com.dfht.modules.miniapp.utils.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @Description: 微信小程序上传接口
 * @Author Ray
 * @Date 2020/10/22 10:04
 * @Version 1.0
 */
@RestController
@RequestMapping("${apiPath}/wx/upload")
public class WxUploadController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 保存文件的路径
    @Value("${miniapp_file_path}")
    private String realPath;


    /**
     * 小程序上传多个文件处理类,保存到本地
     * 注意:前端必须要处理好文件名,后端无法处理
     */
    @RequestMapping("/file")
    public AjaxResult file(HttpServletRequest request) throws IOException {
        logger.info("开始执行文件上传");
        request.setCharacterEncoding("UTF-8");

        String message = "";

        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //resolver.setMaxUploadSize(1000000);
        resolver.setDefaultEncoding("UTF-8");

        if (!resolver.isMultipart(request)) {
            return AjaxResult.error();
        }

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();

        while (it.hasNext()) {
            MultipartFile file = multiRequest.getFile(it.next());
            if (!file.isEmpty()) {
                logger.info("获取文件成功");
                String fileName = file.getOriginalFilename();
                String name = file.getName();
                System.out.println("name = " + name);
                String path = "";
                String type = "";
                type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : "";
                logger.info("文件初始名称为:" + fileName + " 类型为:" + type);

                if (StringUtils.isNotBlank(type)) {
                    // 判断目录是否存在
                    File dir = new File(realPath);
                    if (!dir.exists()) {
                        dir.mkdirs();//创建目录
                        logger.info(realPath + " 文件夹不存在,自动创建目录");
                    }

                    // 自定义的文件名称
                    String trueFileName = fileName;
                    // 设置存放图片文件的路径
                    path = realPath + trueFileName;
                    logger.info("存放文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");

                } else {
                    message = "文件类型为空";
                    logger.error(message);
                    return AjaxResult.error(message);
                }
            } else {
                message = "没有找到相对应的文件";
                logger.error(message);
                return AjaxResult.error(message);
            }
        }

        return AjaxResult.success(message);
    }
}

utils

代码语言:javascript
复制
package com.dfht.modules.miniapp.utils;

import cn.hutool.core.util.ObjectUtil;

import java.util.HashMap;

/**
 * 操作消息提醒
 * 
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object>
{
    private static final long serialVersionUID = 1L;

    /** 状态码 */
    public static final String CODE_TAG = "code";

    /** 返回内容 */
    public static final String MSG_TAG = "msg";

    /** 数据对象 */
    public static final String DATA_TAG = "data";

    /**
     * 状态类型
     */
    public enum Type
    {
        /** 成功 */
        SUCCESS(200),
        /** 警告 */
        WARN(301),
        /** 错误 */
        ERROR(500);
        private final int value;

        Type(int value)
        {
            this.value = value;
        }

        public int value()
        {
            return this.value;
        }
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
     */
    public AjaxResult()
    {
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     * 
     * @param type 状态类型
     * @param msg 返回内容
     */
    public AjaxResult(Type type, String msg)
    {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     * 
     * @param type 状态类型
     * @param msg 返回内容
     * @param data 数据对象
     */
    public AjaxResult(Type type, String msg, Object data)
    {
        super.put(CODE_TAG, type.value);
        super.put(MSG_TAG, msg);
        if (ObjectUtil.isNotNull(data))
        {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     * 
     * @return 成功消息
     */
    public static AjaxResult success()
    {
        return AjaxResult.success("操作成功");
    }

    /**
     * 返回成功数据
     * 
     * @return 成功消息
     */
    public static AjaxResult success(Object data)
    {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回内容
     * @return 成功消息
     */
    public static AjaxResult success(String msg)
    {
        return AjaxResult.success(msg, null);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static AjaxResult success(String msg, Object data)
    {
        return new AjaxResult(Type.SUCCESS, msg, data);
    }

    /**
     * 返回警告消息
     * 
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult warn(String msg)
    {
        return AjaxResult.warn(msg, null);
    }

    /**
     * 返回警告消息
     * 
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult warn(String msg, Object data)
    {
        return new AjaxResult(Type.WARN, msg, data);
    }

    /**
     * 返回错误消息
     * 
     * @return
     */
    public static AjaxResult error()
    {
        return AjaxResult.error("操作失败");
    }

    /**
     * 返回错误消息
     * 
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult error(String msg)
    {
        return AjaxResult.error(msg, null);
    }

    /**
     * 返回错误消息
     * 
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult error(String msg, Object data)
    {
        return new AjaxResult(Type.ERROR, msg, data);
    }
}

输出结果

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-10-22|,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 小程序端
    • wxml
      • wxss
        • js
          • 界面
            • 初始界面
            • 上传图片
            • 预览图片
            • 删除图片
            • 发布图片
        • Java 端
          • properties
            • controller
              • utils
                • 输出结果
                相关产品与服务
                云开发 CloudBase
                云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档