参考
参考
简单来说是先执行upload到后台,controller将图片保存到服务器后将图片路径通过json返回小程序,在upload sucess时setData存储路径。然后调用wx.request
var that=this;
wx.uploadFile({
url: 'http://127.0.0.1:8080/xcxmvc/film/uploadPic',//
filePath: that.data.src,
name: 'uploadfile_ant',
header: {
'content-type': 'multipart/form-data'
},
formData: null,
success: function (res) {
var data = JSON.parse(res.data);
that.setData({src:data.src});//存储图片路径
//
//在upload执行success后 执行wx.request
wx.request({
url: 'http://127.0.0.1:8080/xcxmvc/username/dl',
data: {
img: that.data.imgsrc,
},
method: 'post',
header: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function (res) {
下面是wxml代码
<button bindtap="bindtest" data-username="{{username.userInfo.nickName}}">oooo</button>
<button bindtap="upload">i</button>
下面是js代码
upload: function () {
this.data.panduanshangchuan=6;//用户点击上传图片后将值从0改为6
let that = this;
wx.chooseImage({
count: 9, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: res => {
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 1000
})
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
let tempFilePaths = res.tempFilePaths[0];
console.log(tempFilePaths);
that.setData({
src: res.tempFilePaths[0]
})
//var filep = res.tempFilePaths[0]
}
})
},
bindtest: function (e) {
console.log(this.data.panduanshangchuan);
if(this.data.panduanshangchuan==0){//如果用户没点击上传图片会提示
wx.showModal({
title: '错误提示',
content: '上传图片失败',
showCancel: false,
success: function (res) { }
})
}
else{
/
//
//上传图片
var that=this;
console.log(that.data.src);
wx.uploadFile({
url: 'http://127.0.0.1:8080/xcxmvc/film/uploadPic',//
filePath: that.data.src,
name: 'uploadfile_ant',
header: {
'content-type': 'multipart/form-data'
},
formData: null,
success: function (res) {
var data = JSON.parse(res.data);
console.log(data); //接口返回网络路径
that.setData({panduan:data.aaa})//将返回的值存进panduan用于判断是否符合扩展名
that.setData({imgsrc:data.src})
// var that = this;
var username = e.currentTarget.dataset.username;
console.log(username);
wx.request({
url: 'http://127.0.0.1:8080/xcxmvc/username/dl',
data: {
//username: '张育嘉',
password: '123',
//var latitude=app.globalData.latitude;/:this.g
img: that.data.imgsrc,
latitude: that.data.latitude,//从全局变量app.js中取
longitude: that.data.longitude,//从data中取
nr: that.data.nr,
username: username,
url6: that.data.src
},
method: 'post',
header: {
//'content-type': 'application/json' // 默认值
'Content-Type': 'application/x-www-form-urlencoded'
},
success: function (res) {
console.log(res.data);
//that.shifoutiaozhuan()
//function lalala();这样能调用别的方法
that.setData({ nr6: res.data.userid, });//这样能获取json单独put的值
//
//
var cc = res.data.userid;//判断是否跳转
console.log(cc);
if (cc < 2 && that.data.panduan < 6) {
console.log("发帖成功");
that.shifoutiaozhuan()
that.setData({ nr66: '发帖成功' })
}
else {
that.fashengcuowu();//调用下面的函数弹窗
}
},
fail: function (res) {
console.log(".....6666.....");
}
})
}
// that.data.picPaths.push(data['msg'])
// that.setData({
// picPaths: that.data.picPaths
})
}
// console.log(that.data.picPaths);
// }
// })
// ————————————————
// 版权声明:本文为CSDN博主「前端_李嘉豪」的原创文章,遵循 //CC 4.0 BY - SA 版权协议,转载请附上原文出处链接及本声明。
// 原文链接:https://blog.csdn.net/weixin_42460570/article/details/81203206
},
下面是上传图片的controller
package control;
//package uploadPicture;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import bean.filedo;
/**
* Created by Administrator on 2018/10/23.
* @param <FileDomain>
*/
@Controller
public class uimg {
//文件类型
public static String IMG_TYPE_PNG = "PNG";
public static String IMG_TYPE_JPG = "JPG";
public static String IMG_TYPE_JPEG = "JPEG";
// public static String IMG_TYPE_DMG = "BMP";
public static String IMG_TYPE_GIF = "GIF";
// public static String IMG_TYPE_SVG = "SVG";
@RequestMapping("/film/uploadPic")
@ResponseBody
public Object uploadPic(MultipartFile uploadfile_ant,HttpServletRequest request,HttpSession s6) throws Exception {
request.getSession().setAttribute("projectid","oo");
String oldName = uploadfile_ant.getOriginalFilename();
String newName = UUID.randomUUID().toString().replace("-", "").toUpperCase()
+ "_" + oldName;
String name= uploadfile_ant.getOriginalFilename();
String filee=name.substring(name.lastIndexOf("."));//(name.lastIndexOf("."));//name.lastIndexOf(".");
// System.out.print(filee+"''''''''''''''''''''''''''''''''''''");
String temp_str="";
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
temp_str=sdf.format(dt);
String path=request.getServletContext().getRealPath("/upload/");
//System.out.println("上传的图片的newName: " + newName+",,,,,,"+temp_str+""+path);
File base = new File(path);
if (! base.exists()) {
base.mkdirs();
}
//if(!(filee.equals(IMG_TYPE_GIF)||filee.equals(IMG_TYPE_PNG)||filee.equals(IMG_TYPE_JPG)||filee.equals(IMG_TYPE_JPEG))){}
// 保存文件
List<String> filelist=new ArrayList<String>();
filelist.add(".png");
filelist.add(".PNG");
HashMap s = new HashMap();
int i;
if(filelist.contains(filee)){
uploadfile_ant.transferTo(new File(path + temp_str+filee));
i=0;
s.put("aaa", i);
//s6.setAttribute("aaa", i);
s.put("session", request.getSession().getId());
s.put("src", path+temp_str+filee);
//request.getSession().setAttribute("img",path+temp_str+filee);
//request.getSession().setAttribute("projectid","oo");
return s;
}
else{
i=6;
s.put("aaa", i);
s6.setAttribute("aaa",i);
// request.getSession().setAttribute("projectid","oo");
return s;
}
// }
}
}
下面是接收图片路径的controller
package control;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import control.serviceusername;
import bean.dao;
import bean.indexdao;
import bean.nrbean;
import bean.sjk;
import bean.userbean;
@Controller
///
//public class username {
// @RequestMapping("/username")
// public String test(@RequestParam("username")String name) {
//;
// System.out.println(name);
// // return "index";
//}
//}
//都能用
@RequestMapping("/username")//用post方式接受表单信息
public class username {
@Autowired
@Resource(name="hql")
private serviceusername s1;
//
///
//jie kou serviceusername
// private cc phone;
//@RequestMapping("/log")
@RequestMapping("/dl")
@ResponseBody
public userbean e(HttpServletRequest request,HttpServletResponse response,userbean user) throws IOException {
//需要request的话需要在这加
response.setContentType("text/html;charset=utf-8");
//����������
request.setCharacterEncoding("utf-8");
//��Ӧ�������
response.setCharacterEncoding("utf-8");
//String name=(String) ((HttpSession) s).getAttribute("aaa");
String id = (String) request.getSession().getAttribute("img");
String username6 = request.getParameter("username");
String username = new String(username6.getBytes("ISO-8859-1"), "UTF-8");
String imgsrc=request.getParameter("img");
System.out.print(imgsrc+";;;;;;;;;;;");
sjk s6=new sjk();
Connection con=null;
// nrbean ne=new nrbean();
// ArrayList nr=null;
dao d=new dao();
// nr=d.getAll();
// String username=request.getParameter("username");
// System.out.print(username);
String pssword=request.getParameter("password");
String url=request.getParameter("url6");
String latitude=request.getParameter("latitude");
//String substring = latitude.substring(-1, latitude.indexOf("."));
//System.out.print(substring);
String longitude=request.getParameter("longitude");
String nr=request.getParameter("nr");
// String openid=request.getParameter("openid");
//System.out.print("llllllllllllllllll"+openid);
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String date6 = df.format(date);
double c;double cc;
c= Double.parseDouble(latitude);//转string为double
cc=Double.parseDouble(longitude);
nrbean nr2=new nrbean();//在bookdao中 public book中定义的
nr2.setData(date6);
nr2.setLatitude(c);
nr2.setLongitude(cc);
nr2.setNr(nr);
nr2.setUsername(username);
nr2.setUrl(url);
//nr2.setInt(id);
boolean a=s1.insert(nr2);
//jiang nr2 fa song dao jie kou s1
///
//System.out.print("fanhui"+a+url+"~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
if(a){
int i=0;
user.setUserid("0");//user shi wei le fan hui json 0 dai biao ok
}
else{//int i=1;
user.setUserid("6");
}
return user;
// @RequestMapping("/dl")
}
//@RequestMapping("/dll")
//@ResponseBody
//public void cc(String username,String password){
// System.out.print(username+password);
// userbean b=new userbean();
//}
@RequestMapping("/dll")
@ResponseBody
public userbean bean(userbean bean,HttpServletRequest request,HttpServletResponse response){
// String session =request.getParameter("session6");
// Cookie cookie=new Cookie("JSESSIONID", session);
// cookie.setPath("/");
// response.addCookie(cookie);
String id = (String) request.getSession().getAttribute("img");
String id6 = (String) request.getSession().getAttribute("projectid");
System.out.print(id+";;;;;;;;;;;"+id6+"....."+request.getSession().getId());
return bean;
}
//---------------------
//作者:云淡风轻58
//来源:CSDN
//原文:https://blog.csdn.net/dwenxue/article/details/81735864
//版权声明:本文为博主原创文章,转载请附上博文链接!
@RequestMapping("/film/uploadPic6")
@ResponseBody
public Object uploadPic(HttpServletRequest request) throws Exception {
request.getSession().setAttribute("projectid","oo");
System.out.println("上传的图片的newName: "+request.getSession().getId());
return request.getSession().getId();
}
// }
}
//}