1. 程式人生 > >SpringBoot使用jQuery File Upload圖片上傳伺服器回顯相關

SpringBoot使用jQuery File Upload圖片上傳伺服器回顯相關

FileUitl.java文字操作工具類

/**
     * 讀取資料流生成圖片
     * @param imageIo
     * @param path
     * @return
     */
    public boolean base64ToImage(String imageIo, String path){
        boolean imageFlag = false;
        FileOutputStream fileOutputStream = null;
        try {
            //把加密的圖片流解密成字元
            byte[] faceBytes = Base64.decodeBase64(imageIo);
            // 生成圖片
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            fileOutputStream = new FileOutputStream(path);
            IOUtils.write(faceBytes, fileOutputStream);
            imageFlag = true;
        } catch (IOException e) {
            logger.error("圖片儲存寫入失敗");
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fileOutputStream);
        }
        return imageFlag;
    }

controller業務

/**
     * 上傳手持身份證照片
     * @param requests
     * @param response
     * @return
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult upload(MultipartHttpServletRequest requests, HttpServletResponse response){
        BaseResult baseResult = new BaseResult();
        Iterator<String> itr =  requests.getFileNames();
        MultipartFile mpf = null;
        //上傳路徑
        String typeUrl="selfie/";
        String str=dateUtil.dateToYYMMDD(new Date()).replace("-","");
        String month=str.substring(0,6);
        String day=str.substring(6);
        //String type="/fronts/images/";
        while(itr.hasNext()){
            mpf = requests.getFile(itr.next());
            String url=IMG_BASE_PATH+typeUrl+month+"/"+day+"/"+mpf.getOriginalFilename();
            try {
                //FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream(url));
                // 生成圖片
                BASE64Encoder encoder = new BASE64Encoder();
                String image=encoder.encode(mpf.getBytes());
                boolean imageFlag = fileUtil.base64ToImage(image, url);
                if(!imageFlag){
                    baseResult.setCode(GlobalCodeEnum.CODE_500.getKey());
                    baseResult.setMessage("轉換成圖片/儲存下來失敗");
                    logger.info("轉換成圖片/儲存下來失敗 type:{}", typeUrl);
                    return baseResult;
                }
                baseResult.setMessage("上傳成功");
                baseResult.setData(url);
                baseResult.setSuccess(true);
            } catch (IOException e) {
                baseResult.setSuccess(false);
                baseResult.setMessage("上傳失敗");
            }
        }
        return baseResult;
    }

html頁面

前端input控制元件需這樣寫:

<input class="upload" id="file" type="file" name="file" accept="image/*"  capture="camera"/>
$('#file').fileupload({
        url:"/front/attach/upload",
        autoUpload: true,
        dataType: 'json',
        maxFileSize: 10485760,
        add:function (e,data) {
            $.each(data.files,function (index) {
                var reg = /gif|jpe?g|png/;
                var type = $(this)[index].type;
                var s = type.replace('image/',"");
                var size = $(this)[index].size;
                if (reg.test(s)&&size<10485760){
                    data.submit();
                }else {
                    layer.msg('您選擇的圖片型別不對或者圖片超過10MB,請重新選擇', {time : 2000}, function(){});
                }
            })
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $('.progress').show().children('.bar').width(progress+'%')
            if (progress==100){
                setTimeout(function () {
                    $('.progress').hide();
                },1000)
            }
        },
        done: function (e, data) {
            console.log(data)
                if (data.result.success) {
                  $('.attach-box .attact-upload .upload-img').hide();
                    $('.attach-box .attact-upload .up-font').hide();
                    //回顯操作
                    var path="/front/attach/downloadMaterialInfo?path="+data.result.data;
                    $('#target').attr('src',path).show();
                    $("#photo").val(data.result.data);
                    $('.reupload').show();
                    layer.msg(data.result.message, {time : 3500}, function(){});
                } else{
                    layer.msg(data.result.message, {time : 3500}, function(){});
                }
        },
        fail:function (e, data) {
            layer.msg("系統錯誤", {time : 3500}, function(){});
        }
    })

從伺服器下載檔案controller

 /**
     * 附件下載
     * @param path
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/downloadMaterialInfo")
    public void downloadMaterialInfo(String path, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream photoInputStream = null;
        OutputStream outputStream = null;
        try {
            if (path == null) {
                //path = request.getSession().getServletContext().getRealPath("/images/unupload.jpg");
                path = getClass().getResource("/static/images/unupload.jpg").getFile();
            }
            File downloadFile = null;
            if (path == null || !(downloadFile = new File(path)).exists()) {
                //path = request.getSession().getServletContext().getRealPath("/images/notFoundImg.png");
                path = getClass().getResource("/static/images/notFoundImg.png").getFile();
                downloadFile = new File(path);
            }
            int length = (int) downloadFile.length();
            String fileName = URLEncoder.encode(downloadFile.getName(), "UTF-8");
            response.reset();
            response.setContentLength(length);
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "No-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            photoInputStream = new FileInputStream(downloadFile);
            outputStream = response.getOutputStream();
            IOUtils.copyLarge(photoInputStream, outputStream);
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(photoInputStream);
        }
    }