600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java 微信图片上传_微信小程序图片上传java端以及前端实现

java 微信图片上传_微信小程序图片上传java端以及前端实现

时间:2023-12-03 08:56:44

相关推荐

java 微信图片上传_微信小程序图片上传java端以及前端实现

小程序的图片上传与传统的图片上传方式有一些不一样

如果你有幸看到这篇文章,恭喜你,你可以完美解决了。

话不多说,前后端代码一并奉上:

(基于springmvc )

@Controller

@RequestMapping("/upload")

public class UploadController {

private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

@RequestMapping("/picture")

public void uploadPicture(HttpServletRequest request, HttpServletResponse response) throws Exception {

//获取文件需要上传到的路径

String path = request.getRealPath("/upload") + "/";

File dir = new File(path);

if (!dir.exists()) {

dir.mkdir();

}

logger.debug("path=" + path);

request.setCharacterEncoding("utf-8"); //设置编码

//获得磁盘文件条目工厂

DiskFileItemFactory factory = new DiskFileItemFactory();

//如果没以下两行设置的话,上传大的文件会占用很多内存,

//设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同

/**

* 原理: 它是先存到暂时存储室,然后再真正写到对应目录的硬盘上,

* 按理来说当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的

* 然后再将其真正写到对应目录的硬盘上

*/

factory.setRepository(dir);

//设置缓存的大小,当上传文件的容量超过该缓存时,直接放到暂时存储室

factory.setSizeThreshold(1024 * 1024);

//高水平的API文件上传处理

ServletFileUpload upload = new ServletFileUpload(factory);

try {

List list = upload.parseRequest(request);

FileItem picture = null;

for (FileItem item : list) {

//获取表单的属性名字

String name = item.getFieldName();

//如果获取的表单信息是普通的 文本 信息

if (item.isFormField()) {

//获取用户具体输入的字符串

String value = item.getString();

request.setAttribute(name, value);

logger.debug("name=" + name + ",value=" + value);

} else {

picture = item;

}

}

//自定义上传图片的名字为userId.jpg

String fileName = request.getAttribute("userId") + ".jpg";

String destPath = path + fileName;

logger.debug("destPath=" + destPath);

//真正写到磁盘上

File file = new File(destPath);

OutputStream out = new FileOutputStream(file);

InputStream in = picture.getInputStream();

int length = 0;

byte[] buf = new byte[1024];

// in.read(buf) 每次读到的数据存放在buf 数组中

while ((length = in.read(buf)) != -1) {

//在buf数组中取出数据写到(输出流)磁盘上

out.write(buf, 0, length);

}

in.close();

out.close();

} catch (FileUploadException e1) {

logger.error("", e1);

} catch (Exception e) {

logger.error("", e);

}

PrintWriter printWriter = response.getWriter();

response.setContentType("application/json");

response.setCharacterEncoding("utf-8");

HashMap res = new HashMap();

res.put("success", true);

printWriter.write(JSON.toJSONString(res));

printWriter.flush();

}

你以为就只有java后端代码吗?

前端代码也拿去

wx.uploadFile({

url: 'https://xxxxxx/upload/picture',

filePath: filePath,//图片路径,如tempFilePaths[0]

name: 'image',

header : {

"Content-Type": "multipart/form-data"

},

formData:

{

userId: 12345678 //附加信息为用户ID

},

success: function (res) {

console.log(res);

},

fail: function (res) {

console.log(res);

},

complete: function (res) {

}

})

经过实践检验,有问题可以下方提问。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。