用Ajax圖片上傳、預覽、修改圖片

首選圖片的上傳和下載並非很難,但要注意細節。javascript

一,給出前端圖片上傳的html代碼html

1.圖片上傳的控件前端

 <img src="/${res}/images/default.png" alt="" class="backimg">
      <form  method="post" id="imgform" enctype="multipart/form-data" action="dy_upload_image.jspx">
          <a href="javascript:;" class="imgstyle">請選擇文件
            <input type="file" name="uploadImage" id="uploadImage">
          </a>
          <input type="button" onclick="gosubmit()" id="imgbtn" value="上傳" />
      </form>

上傳圖片要注意給出默認圖片,提交按鈕是btton、並非submit ,屬性是   enctype="multipart/form-data" 這樣後臺才能接收到上傳的文件。java

2.圖片上傳的jsajax

(1)首次加載的jsapp

$.ajax({
            url:'dy_firstget_image.jspx',
            type:'get',            
            data:{recid:str},
            success:function(info){
                $('.backimg').attr('src',JSON.parse(info).msg)
                console.log(info)
            },
            error:function(err,errmsg){
                console.log(errmsg)
            }
        })

(2)點擊上傳時的jsjsp

function gosubmit(){
            var formdata=new FormData();
            //formdata.append('name', 'uploadImage');
            formdata.append('uploadImage',$('#uploadImage').get(0).files[0]);
            formdata.append('recid',str);
            $.ajax({
                url:'dy_upload_image.jspx',
                type:'post',
                contentType:false,
                data:formdata,
                processData:false,
                success:function(info){    
                    console.log(info)
                    $('.backimg').attr('src',JSON.parse(info).msg);
                },
                error:function(err){
                    console.log(err)
                }
            });
        }    

這裏用到了formdata ,我理解的是用ajax 提交的方式將表單提交上去,由於form表單正常submit提交會跳到下一個界面。用ajax提交能夠在本頁面預覽圖片,用戶體驗很好。post

把圖片數據放到fordata中注意上面紅色js的代碼,是後面controller接到數據的關鍵。ui

先把圖片掛上去,昨天的成果(笑臉)url

 

3,後臺接收圖片的controller(首次加載圖片,若是沒有圖片則顯示默認圖片)

/**
     * 首次加載預覽圖片
     * @param request
     * @param response
     * @param imageName
     */
    @RequestMapping(value = "/dy_firstget_image.jspx", method = RequestMethod.GET)
    public void dy_firstget_image(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "recid", required = false) String recid) {
        response.setContentType("image/jpeg");
        if(!StringUtils.isEmpty(recid)){
            BaseInfoManageBean baseBean = cmsDyUploadImageDaoImpl.getDXYQSBImageByid(recid);
            //根據id查詢該儀器的圖片,若是不爲空則返回圖片url
            if(!StringUtils.isEmpty(baseBean.getPhoto())){
                ResponseUtils.renderText(response, DyUtils.getJSONString(0, baseBean.getPhoto()));
            }
        }
    }

4,上傳圖片方法

    /**
     * 上傳圖片、而且把照片url存儲到大型儀器表中
     * @param request
     * @param response
     * @param file
     * @param recid
     */
    @RequestMapping(value = "/dy_upload_image.jspx", method = RequestMethod.POST)
    public void dy_upload_image(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "uploadImage", required = false) MultipartFile file,
            @RequestParam(value = "recid", required = false) String recid) {
        if(file!=null){
            String imageUrl = cmsDyUploadImageDaoImpl.saveImage(file, recid);
            if(imageUrl!=null){
                ResponseUtils.renderText(response, DyUtils.getJSONString(0, imageUrl));
                return;
            }
        }
        ResponseUtils.renderText(response, DyUtils.getJSONString(1, "圖片上傳失敗"));
    }

上傳成功後返回imageUrl 賦值到img控件上面

<img src="http://127.0.0.1:8080/bjnxy/dy_get_image.jspx?imageName=537e902607944b04a45a3d62d0bd28a3.jpg" alt="" class="backimg">

5,預覽圖片方法

/**
     * 預覽圖片
     * @param request
     * @param response
     * @param imageName
     */
    @RequestMapping(value = "/dy_get_image.jspx", method = RequestMethod.GET)
    public void dy_get_image(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "imageName", required = false) String imageName) {
        response.setContentType("image/jpeg");
        try {
            StreamUtils.copy(new FileInputStream(new File(DyUtils.IMAGE_DIR+imageName)), response.getOutputStream());
        }  catch (IOException e) {
            e.printStackTrace();
            ResponseUtils.renderText(response, DyUtils.getJSONString(1, "讀取圖片失敗"));
        }
    }
相關文章
相關標籤/搜索