微信小程序端实现图片上传功能(后台java)

第一步,选择图片:wx.chooseImage()

第二步,上传图片:wx.uploadFile()

第三步,显示图片。

下面直接上代码(wxml代码我这边就不展示了)

public AjaxResult batch() {
		AjaxResult result = new AjaxResult();
		try {
			Long merchantId = getMerchantIdByToken();
			int uploadType = Integer.parseInt(ServletUtils.getHeaderByName("uploadType"));

			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("UTF-8");
			List<FileItem> items = upload.parseRequest(ServletUtils.getRequest());
			logger.info("本次上传的文件数量:{}", items.size());

			List<String> resultFileUrls = new ArrayList<String>();
			for (FileItem item : items) {
				String name = item.getFieldName();
				logger.info("fieldName:{}", name);

				String folder = UploadTypeEnum.getByTargetType(uploadType).getFolder();

				// 判断是否是一个一般的表单域, 
				if (!item.isFormField()) {
					InputStream is = item.getInputStream();

					//创建文件目录
					String path = profile + merchantId + File.separatorChar + folder + File.separatorChar + item.getName();
					File file = new File(path);
					File fileParent = file.getParentFile();
					if (!fileParent.exists()) {
						fileParent.mkdirs();
					}
					file.createNewFile();

					FileOutputStream fos = new FileOutputStream(path);
					byte[] buff = new byte[1024];
					int len = 0;
					while ((len = is.read(buff)) > 0) {
						fos.write(buff);
					}
					is.close();
					fos.close();

					resultFileUrls.add("http://" + fileServerDomain + "/" + merchantId + "/" + folder + "/" + item.getName());
				}
			}
			result = AjaxResult.success("上传文件成功").putListData(resultFileUrls);
		} catch (Exception e) {
			result = AjaxResult.error("上传文件异常");
			e.printStackTrace();
		}
		return result;
	}

后台文件上传接口可以自己定义封装文件路径,比较灵活,不需要生搬硬套。我这边建议是按照一定的规则、归类存取,这样对于比较多文件的情况下方便查找。那么接下来你亲自操作一遍试试?有问题我们再探讨。

经验分享 程序员 微信小程序 职场和发展