卜若的程式碼筆記系列-微信小程式系列-第二章:微信小程式獲得srpingboot返回的json資料-4002
阿新 • • 發佈:2018-12-13
1.微信端向伺服器傳送上傳請求
wx.chooseImage({ success: function (res) { var tempFilePaths = res.tempFilePaths console.log(tempFilePaths[0]) wx.uploadFile({ url: 'http://xxxx/xxx/xx', filePath: tempFilePaths[0], name: "rawPic", }) } })
2.伺服器控制器
@PostMapping("/uploadPic") public Result uploadPic( @RequestParam(required=true,name="rawPic") MultipartFile file ) { String path = write.writePicPath(); Result result = new Result(); result.setCode(1); result.setMessage(write.getFilepPath()+"\\"+path); try { file.transferTo(new File(write.getFilepPath()+"\\"+path)); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
看不懂伺服器程式碼的同學可以參考我的springboot的相關部落格
現在要說的是,springboot支援直接返回物件,物件的所有欄位全部通過getset訪問器 設定為屬性,將會以json格式傳給客戶端,所以你根本不用操心在伺服器端怎麼轉json!
這是返回物件的程式碼
public class Result { private int code; private String message; private Object data; public Result setCode(ResultCode resultCode) { this.code = resultCode.code; return this; } public int getCode() { return code; } public Result setCode(int code) { this.code = code; return this; } public String getMessage() { return message; } public Result setMessage(String message) { this.message = message; return this; } public Object getData() { return data; } public Result setData(Object data) { this.data = data; return this; } @Override public String toString() { return JSON.toJSONString(this); } }
3.客戶端可以通過轉json格式獲取裡面的資料,就像讀字典一樣,超級爽!
success(res)
{
console.log(JSON.parse(res.data)['message']);
}