小程序js
//启动上传等待中... wx.showToast({ title: '正在上传...',icon: 'loading',mask: true,duration: 10000 }) //上传图片 wx.uploadFile({ url: '***********',//上传的路径(Java后台路径) filePath: tempFilePaths[0],name: 'file',success: function (res) { console.log(res.data)//oss图片路径 wx.showToast({ title: "上传成功",icon: 'success',duration: 1000 }) },fail: function ({ errMsg }) { wx.showToast({ title: "上传失败",})
Java后台
@RequestMapping("/programImg") public @ResponseBody String programImg(@RequestParam(required = false) MultipartFile file,HttpServletRequest request) { File targetFile=null; String str="";//返回存储路径 String fileName=file.getOriginalFilename();//获取文件名加后缀 if(fileName!=null&&fileName!=""){ String returnUrl = ”*****“;//服务器存储路径 String fileF = FilenameUtils.getExtension(file.getOriginalFilename());//文件后缀 fileName=”*****************“;//新的文件名 //先判断文件是否存在,获取文件夹路径 File file1 =new File(returnUrl); //如果文件夹不存在则创建 if(!file1 .exists() && !file1 .isDirectory()){ file1 .mkdir(); } //将图片存入文件夹 targetFile = new File(file1,fileName); try { //将上传的文件写到服务器上指定的文件。 file.transferTo(targetFile); String gifName = "******";//图片oss上传根目录 String url=gifName+"/"+fileName; putObject(targetFile,gifName,fileName); str=““;//oss图片路径 } catch (Exception e) { e.printStackTrace(); } } return str; } public static void putObject(File file,String fileName,String fileName){ OSSClient ossClient=null; try { //初始化oss ossClient = ossIni(); //上传路径 String route=fileName+"/"+fileName; //上传图片 img-program--Bucket名称 ossClient.putObject("img-program",route,file); } catch (Exception e) { if (ossClient!=null) { ossClient.shutdown(); } e.printStackTrace(); } ossClient.shutdown(); } private static OSSClient ossIni(){ OSSClient ossClient = null; try { ossClient = new OSSClient(ENDPOINT,KEY_ID,KEY_SECRET); System.out.println("oss 初始化成功"); } catch (Exception e) { e.printStackTrace(); } return ossClient; } public static final String ENDPOINT="****************"; public static final String KEY_ID="*****************"; public static final String KEY_SECRET="****************";原文链接:https://www.f2er.com/java/534949.html