页面
<view>网络接口</view>
<button bindtap="handleTap">发送请求</button>
<view>文件下载接口</view>
<button bindtap="tapdownload">点击下载</button>
<image src="{
{url}}"/>
<view>文件上传接口</view>
<view class="container">
<button type="primary" bindtap="taphandler">点击上传</button>
</view>
JS
Page({
data: {
url: ""
},
handleTap(e) {
wx:wx.request({
url: 'http://localhost/helloworld',
data: {
x: '1',
y: '2'
},
enableCache: true,
enableHttp2: true,
enableQuic: true,
method: "GET",
timeout: 0,
success: (result) => {
console.log("request success!");
console.log(result.data);
},
fail: (res) => {
console.log("request failed!");
console.log(res.data);
},
complete: (res) => {
console.log("request complete");
},
})
},
tapdownload(e) {
wx.downloadFile({
url: 'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2573117116,2199107723&fm=26&gp=0.jpg',
success: (res)=> {
console.log("success " + JSON.stringify(res));
this.setData({
url: res.tempFilePath
})
},
fail: (err)=> {
console.log("fail " + JSON.stringify(err));
},
complete: (e)=> {
console.log("complete " + JSON.stringify(e));
}
})
},
taphandler(e) {
wx.chooseImage({
count: 3,
sizeType: ['original', 'compressed'],
success: (res)=> {
console.log("success");
wx.uploadFile({
filePath: res.tempFilePaths[0],
name: 'test',
url: 'http://localhost/upload',
formData: {
name: 'tom',
age : 18
},
success: (res)=>{
console.log("upload success");
},
fail: (err)=>{
console.log(err);
},
complete: (e)=>{
console.log("upload complete");
}
})
},
fail: (err)=> {
console.log("fail");
},
complete: (e)=> {
console.log("complete");
}
})
},
onLoad: function (options) {
},
onReady: function () {
},
onShow: function () {
},
onHide: function () {
},
onUnload: function () {
},
onPullDownRefresh: function () {
},
onReachBottom: function () {
},
onShareAppMessage: function () {
}
})
后台
@RestController
public class HelloWorldController {
@GetMapping("/helloworld")
public Person helloworld(String x, String y) {
Person person = new Person();
person.setName("tom");
person.setId(Long.parseLong(x));
person.setAge(Integer.parseInt(y));
return person;
}
@PostMapping("/upload")
public Person upload(@RequestParam("name") String name, @RequestParam("age")Integer age,
@RequestParam("test")MultipartFile test, HttpServletRequest request) {
Person person = new Person();
person.setName(name);
person.setAge(age);
String originalFilename = test.getOriginalFilename();
String path = request.getSession().getServletContext().getRealPath("upload");
File targetFile = new File(path, originalFilename);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
test.transferTo(targetFile);
}catch (Exception e) {
e.printStackTrace();
}
return person;
}
}