ajax上传图片并回显

最近学习了一下上传图片并且写了个demo 活不多说 直接上代码

首先 你需要引入ajaxfileupload.js 和 jquery
其次新建一个页面代码如下

<tr>  <div class="uploadPicture">     
<td style="text-align:right;">图片地址:
</td> <td style="text-align:left;"> 
    <img alt="" src="" id="imgAD" width="100px"> 
    <input type="file" name="basicInfoAD" id="basicInfoAD" onchange="uploadAD();" /> 
    <input type="hidden" name="imgUrl" id="imgUrl" ><!-- 图片成功上传后的url --> 
然后便是我们的js了
<script type="application/javascript" src="../js/jquery-1.9.1.min.js"></script>
<script type="application/javascript" src="../js/ajaxfileupload.js"></script>
<script type="application/javascript">
        function uploadAD(){
            var file = document.getElementById("basicInfoAD");
            var formdata = new FormData();
            formdata.append("file",file.files[0]);
            $.ajax({
                url:"${pageContext.request.contextPath}/uploadAD",
                method:"post",
                data:formdata,
                dataType: 'json',
                processData: false,  // 告诉jQuery不要去处理发送的数据
                contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    alert(data);
                    console.log("${pageContext.request.contextPath}");
                    alert(${pageContext.request.contextPath});
                    $("#imgAD").attr("src","${pageContext.request.contextPath}/"+data.filename);
                    $("#imgUrl").val("${pageContext.request.contextPath}/"+data.filename);
                } ,error:function(){
                    alert('上传失败!');                   
                }
            });
        };
   
        }

</script>

最后就是controller 代码如下

package com.example.spring;

import com.alibaba.fastjson.JSON;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.apache.catalina.Manager;
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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description:
 * @Author: zhujianli
 * @CreateDate: 2018/9/27 14:56
 * @Version: 1.0
 */
@Controller
public class Demo3Controller {
    /*** 方法名称:
     * ajaxUploadAD   
     * * 方法作用:    
     * ajax 上传图片*/
    @RequestMapping(value = "uploadAD", produces = "text/plain;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
    public String ajaxUploadAD(HttpServletRequest request) throws IllegalStateException, IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        String fileName = "";
        String uploadPath = "image";
        String path =request.getSession().getServletContext().getRealPath("/") +uploadPath;
        System.out.println(path);
         File uploadPathFile = new File(path);
         if (!uploadPathFile.exists()){
             uploadPathFile.mkdir();
         }
        for (Iterator it = multipartRequest.getFileNames(); it.hasNext(); ) {
            String key = (String) it.next();
            MultipartFile mulfile = multipartRequest.getFile(key);
            fileName = mulfile.getOriginalFilename();
            fileName = handlerFileName(fileName);
            File file = new File(path , fileName);
            mulfile.transferTo(file);
        }
        Map<String,String> result = new HashMap<>();
        result.put("filename",uploadPath+"/"+fileName);
        return JSON.toJSONString(result);
    }

    /*** 方法名称: handlerFileName   
     * * 方法作用:    
     * 文件名称处理,
     * 获取唯一想要的文件名*/
    private String handlerFileName(String fileName) {
      fileName = (new Date()).getTime() + "_" + fileName;
      return fileName;
    }


    }



自己已经测试过没有问题

猜你喜欢

转载自blog.csdn.net/csdn_myprogramLife/article/details/82917684