Premier : implémentation de l'image de téléchargement dans le navigateur ;
Deuxièmement : implémentation de l'image de téléchargement de l'applet WeChat
1. pour télécharger des fichiers image sur WeChat ou une application mobile :
package cn.ncist.tms.attachment.controller; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; /** * 附件上传类 * * @author Fxh * */ @RequestMapping(value = "/fileUpload") @Controller public class AttachmentUpload { /** * 上传文件功能,以Post请求发送请求, * * @param request:请求对象 * @param reponse:响应对象 * @param file:上传的文件对象 * @return JSON串 : {"code":"S","msg":"服务调用成功"} * @throws IOException */ @RequestMapping(value = "/doFileUpload",method = RequestMethod.POST) @ResponseBody public Map<String,Object> doFileUpload(HttpServletRequest request, HttpServletResponse reponse, @RequestParam("file") MultipartFile srcFile) throws IOException{ /* * 注意:传入参数时,文件的注解@ReuqestParam("variable") -->variable指:前端的h6的控件的name值. * * 文件处理功能: 1.将获取的字节数组转化为文件对象,并保存在本地目录中; * * 文件处理思路: 1.将获取的(source)file对象,通过函数获取字节数组; * 2.实例化文件对象和文件输出流; * 3.将字节数组写入文件即可. * * 功能难度: 简单. */ //1.变量声明 Map<String,Object> result = null;// 返回结果变量 FileOutputStream fos = null; //写入文件的变量 File destFile = null; //写入的目的地文件(distination) try { result = new HashMap<String,Object>(); //2.参数验证 if(srcFile == null){ throw new RuntimeException("上传文件不存在"); } if(srcFile.getBytes().length == 0){ throw new RuntimeException("上传文件内容为空"); } //3.操作文件对象,写入本地目录的文件中 //3.1 截取文件后缀 String ext = srcFile.getOriginalFilename().substring(srcFile.getContentType().lastIndexOf( ".")+1); //3.2 实例化目标文件,根据当前的操作系统,指定目录文件, destFile = new File("D:"+File.separator+"descFolder"+File.separator+"descFile."+ext); //3.3 实例化流 fos = new FileOutputStream(destFile); //3.4 获取写入的字节数组,并写入文件 byte[] srcBytes = srcFile.getBytes(); fos.write(srcBytes); fos.flush(); //4.对输入、输出流进行统一管理 //已在文件finally代码块处理 result.put( "code", "S"); result.put( "msg", "服务调用成功"); result.put( "path", destFile.getAbsolutePath()); return result; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); result = new HashMap<String,Object>(); result.put( "code", "F"); result.put( "msg", "服务调用失败"); result.put( "path", null); return result; } finally{ //关闭系统资源,避免占用资源. if(fos != null){ fos.close(); } } } }
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!