ajax上传文件(以图片为例) SpringMVC

    xiaoxiao2021-03-25  116

    1.首先写出一个表单,设置表单属性

    <form id="tableForm" name="tableForm" enctype="multipart/form-data"> <input style="margin-left: 10px;" type="file" id="img" name="img" class="form-control"> <img id="imgShow" src="" width="250px" height="250px" οnerrοr="javascript:this.src='<%=basePath%>/images/timg.jpg'"> </form>

    tips:enctype="multipart/form-data" 必须有

    2.为了更好的用户体验,我们可以显示出用户所选择的图片

    /*图片上传预览*/ $("#img").on("change",function() { // Get a reference to the fileList var files = !!this.files ? this.files : []; // If no files were selected, or no FileReader support, return if (!files.length || !window.FileReader){ return; }; // Only proceed if the selected file is an image if (/^image/.test(files[0].type)) { // Create a new instance of the FileReader var reader = new FileReader(); // Read the local file as a DataURL reader.readAsDataURL(files[0]); // When loaded, set image data as background of div reader.onloadend = function() { $("#imgShow").prop("src",this.result ); } }else{ layer.alert('请选择正确的图片格式!'); $("#img").val(''); $("#imgShow").prop("src",''); } }); tips:此段代码中用到$("#img").val('');用来在用户选择了错误图片类型时,清除文件上传框的内容,并且此处只能传递空的字符串‘’,无法传递值。

    3.提交表单:

    var formData = new FormData($("#tableForm")[0]); //获取表单内容 $.ajax({ url : contextPath + "/user/save", type : "POST", data : formData, cache : false, contentType : false, processData : false, success : function(data){ alert("上传成功!"); }, });

    tips:此处获取表单内容的方法为html5内置,可以获取表单内的文件信息,故选用此方法。ajax方法中不能添加datatype:“json“属性。cache、contentType、processData属性需要有。可以在表单中添加附加数据:formData.append("name","hu");

    4.后台接受文件:

    @ResponseBody @RequestMapping(value = "save", method = RequestMethod.POST) public void save(@RequestParam(value = "img", required = false) MultipartFile file,HttpServletRequest request) { User user = new User(); user.setName(request.getParameter("name")); if (file.getSize() != 0) { //判断是否有文件 user.setImg(FileUpload.upload(file, request)); // 使用工具类上传文件 } } tips:文件特殊接收,且此时无法再用对象直接接收前台传来的数据,所以我们需要从request对象中获取。

    5.文件上传(工具类):

    public class FileUpload { public static String upload(MultipartFile file,HttpServletRequest request){ String path = request.getSession().getServletContext().getRealPath("upload/img"); //图片存放文件夹 String fileName=new String(); //放置的文件名 String backName=new String(); //返回的文件所在相对路径以及文件名 if(file==null){ //无文件上传 fileName=""; }else{ try { fileName = file.getOriginalFilename(); //获取文件名称(可修改为时间戳) backName=fileName; //设置文件返回名称(可自由配置) File targetFile = new File(path, fileName); //放入文件 if (!targetFile.exists()) { //如果文件不存在 targetFile.mkdirs(); //绘制文件 } file.transferTo(targetFile); //文件上传 } catch (Exception e) { e.printStackTrace(); } } return backName; //返回文件名称 } } tips:推荐将文件名根据自己情况改为时间戳等形式,最好不要带有中文(此处为省时间,无转换)。

    转载请注明原文地址: https://ju.6miu.com/read-3559.html

    最新回复(0)