微信小程序上传图片到服务器(java后台以及使用springmvc)

小程序代码:

image.wxml

  <form bindsubmit="uploadImg">
    <label bindtap="chooseimage">点击选择图片</label>
       <view class="img" wx:for="{{imgs}}" wx:for-item="item" wx:key="*this">
         <image src="{{item}}" data-index="{{index}}" mode="widthFix" bindtap="previewImg" bindlongpress="deleteImg"></image>
      </view>
    <button form-type="submit">提交</button>
  </form>

image.js代码:

 //上传图片
  chooseImg: function (e) {
    var that = this;
    var imgs = this.data.imgs;
    if (imgs.length >= 9) {
      this.setData({
        lenMore: 1
      });
      setTimeout(function () {
        that.setData({
          lenMore: 0
        });
      }, 2500);
      return false;
    }
    wx.chooseImage({
      // count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        // console.log(tempFilePaths + '----');
        for (var i = 0; i < tempFilePaths.length; i++) {
          if (imgs.length >= 9) {
            that.setData({
              imgs: imgs
            });
            return false;
          } else {
            imgs.push(tempFilePaths[i]);
          }
        }
        that.setData({
          imgs: imgs
        });
      }
    });
  },
//保存到服务器
    upload_file: function () {
      var that = this;
     
      wx.uploadFile({
        url: "接口地址",
        filePath: that.data.imgs[0],
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        }, // 设置请求的 header
        formData: { 'type': "jstyle" }, // HTTP 请求中其他额外的 form data
        success: function (res) {
          wx.showToast({
            title: "图片上传成功",
            icon: 'success',
            duration: 700
          })
        },
        fail: function (res) {
        }
      })
    },

java后台代码:

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
 
/**
 * 商品信息页面跳转控制类
 * @author a柴大队长
 * @createtime 2017年8月20日10:34:55
 */
@Controller
@RequestMapping("goods")
public class GoodsController {
 
    private Logger logger = Logger.getLogger(GoodsController.class);
 
    /**
     * @createtime 2017年8月20日17:15:41
     * @param request
     * @param file
     * @return 上传成功返回“success”,上传失败返回“error”
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping("upload")
    public String upload(HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        System.out.println("执行upload");
        request.setCharacterEncoding("UTF-8");
        logger.info("执行图片上传");
        String user = request.getParameter("user");
        logger.info("user:"+user);
        if(!file.isEmpty()) {
            logger.info("成功获取照片");
            String fileName = file.getOriginalFilename();
            String path = null;
            String type = null;
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            logger.info("图片初始名称为:" + fileName + " 类型为:" + type);
            if (type != null) {
                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) {
                    // 项目在容器中实际发布运行的根路径
                    String realPath = request.getSession().getServletContext().getRealPath("/");
                    // 自定义的文件名称
                    String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
                    // 设置存放图片文件的路径
                    path = realPath + "/uploads/" + trueFileName;
                    logger.info("存放图片文件的路径:" + path);
                    file.transferTo(new File(path));
                    logger.info("文件成功上传到指定目录下");
                }else {
                    logger.info("不是我们想要的文件类型,请按要求重新上传");
                    return "error";
                }
            }else {
                logger.info("文件类型为空");
                return "error";
            }
        }else {
            logger.info("没有找到相对应的文件");
            return "error";
        }
        return "success";
    }
}

到这里就很成功了,图片已经在服务器上了,我的图片在F:\workspaceSVN\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\jstyle_activity\upimage里面,大家可以参考这个地址找一下。

这个文章也供参考,很详细:https://blog.csdn.net/qq_16741383/article/details/77427555

猜你喜欢

转载自blog.csdn.net/m0_37865510/article/details/81223757