文件随表单通过ajax上传或通过BASE64流上传

表单设置
<form class="layui-form" id="related_company_form" action="" lay-filter="related_company_form" enctype="multipart/form-data" method="post">
</form>
获取表单数据
var formSatellite = document.getElementById("related_company_form");//获取所要提交form的id
var formData = new FormData(formSatellite);
通过ajax提交
addRelatedCompany: function(formData ) {
    $.ajax({
        url: urls['add_related_company'],
        type: 'post',
        data: data,
        async : false,
        contentType: false,   //jax 中 contentType 设置为 false 是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不           能正常解析文件
        processData: false,
        success: function (result) {
            if(result && result.success) {
              
            }
        }
    });
}

后台获取文件及表单数据

@RequestMapping(value = "/add_related_company", method = RequestMethod.POST)
public WebResponseContext addRelatedCompany(
    @Validated RelatedCompanyForm form,
    BindingResult bindingResult,
    HttpServletRequest request,
    @RequestParam("sealFile") MultipartFile file
) {
    try {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        if (fieldErrors.size() > 0) {
            return ResponseUtil.error(ValidationUtility.buildingFieldErrors(fieldErrors));
        }
        if (!file.isEmpty()) {
            /*上传根目录*/
            String rootDir = archivedUploadProperties.getSealStorageRootPath();
            /*上传相对路径*/
            String uploadPath = "/images/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";

            /*源文件名*/
            String originalFileName = file.getOriginalFilename();

            String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

            /*上传文件名*/
            String fileName = DateTimeUtility.formatToday(DateTimeUtility.YYYYMMDDHHMMSSS) + suffix;

            /*上传到阿里云存储*/
           //src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAoHBwgH..."
           //base64就是这种格式的啊,转换的时候要把前面的data:image/jpeg;base64,这一段给去掉
           /* 通过base64流转换为文件
              int index = form.getSealStream().indexOf(";base64,");
              String streamStr = form.getSealStream().substring(index + 1);
              byte[] bytes1 = decoder.decodeBuffer(streamStr);
              InputStream  stream = new ByteArrayInputStream(bytes1);
              cloudObjectStorageService.upload(rootDir + uploadPath, fileName, stream);
           */
            if (serverProperties.getStorageType() == 1) {
                cloudObjectStorageService.upload(rootDir + uploadPath, fileName, file.getInputStream());//直接获取文件流
            }
            form.setSeal(uploadPath + fileName);
        }
        Long userId = (Long) request.getSession().getAttribute(
            SecurityConstant.SESSION_AUTH_LOGIN_KEY
        );
        accountService.addRelatedCompany(form, userId);
        return ResponseUtil.success(true);
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage(), e);
        return ResponseUtil.error(e.getLocalizedMessage());
    }
}

//前端通过base64流展示图片,后端只需把文件转为base64流返回前端即可@RequestMapping(value = "/get_base64") public WebResponseContext encodeBase64File(String seal) throws IOException { if (StringHelper.isNotEmpty(seal)) { int index = seal.lastIndexOf("/"); String fileName = seal.substring(index + 1); int index2 = fileName.lastIndexOf("."); String type = fileName.substring(index2 + 1); String localPath = serverProperties.getMessageTempRootPath() + "/fax/images/" + fileName; File localFile = new File(localPath); //下载回执报文到本地 cloudObjectStorageService.download(archivedUploadProperties.getSealStorageRootPath() + seal, localFile); FileInputStream inputFile = new FileInputStream(localFile); byte[] buffer = new byte[(int) localFile.length()]; inputFile.read(buffer); inputFile.close(); localFile.delete(); return ResponseUtil.success("data:image/" +type + ";base64," +new BASE64Encoder().encode(buffer).replaceAll("\r|\n","")); } return ResponseUtil.success(""); }

发布了68 篇原创文章 · 获赞 19 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/tyjlearning/article/details/102657040
今日推荐