文件上传关于Struts2和注解开发SpringBoot的区别

记录前几天strus2和springboot中关于文件上传后台的一些区别:

前台使用了jquery-form的表单ajax回调

<form id="uploadForm" enctype="multipart/form-data" method="POST" name="upfileform"
      target="nm_iframe">
    <input type="file" id="uploadInput"
           style="opacity: 0;width: 80px;height:30px;" name="upload"
           onchange="uploadfile()"/>
</form>
/**
 * 表单初始化
 */
function initFormSubmit() {
    options = {
        url: '/wtfk/upLoadFile.action',      //默认是form的action,如果声明,则会覆盖
        type: 'post',   //默认是form的method,如果声明,则会覆盖
        async: false,
        dataType: 'json',  //接受服务端返回的类型
        //提交后的回调函数
        success: function (data) {
            if (data.success) {
                $('#uploadInput').hide();
                window.setTimeout(function () {
                    $('.info-font').attr("onclick", "reportFile()");
                    $('.info-font').css("opacity", "1");
                    $('.addFont').hide();
                    $('.addLink').hide();
                    $.cookies.set('GUID', data.GUID);
                    // data.fileName = decodeURIComponent(data.fileName,true);
                    // console.log(encodeURI(encodeURI(data.fileName)));
                    // json1 = eval("(" + data.fileName + ")");
                    // console.log(json1);
                    $.cookies.set('fileName', data.fileName);
                    $('.pfile').show();
                    $('.file')[0].innerHTML = data.fileName;
                    layer.msg("文件上传成功!");
                }, 500)
            } else {
                layer.msg(null == data.message ? '附件上传失败' : data.message);
                $("#uploadInput")[0].value = '';
                $('.infofont').attr("onclick", "reportFile()");
                $('.infofont').css("opacity", "1");
            }
        },
    };
    //为表单绑定提交事件,触发后可返回回调函数
    $('#uploadForm').submit(function () {
        $(this).ajaxSubmit(options);
        return false;
    });
}

当获取到到表单对象后执行form.submit()后触发回调函数options。

后端:

使用springboot注解开发,使用MultipartFile接受文件对象,它有自己常见的一些工具方法可供调用。

@RequestMapping("upLoadFile")
@ResponseBody
@RequiresGuest
public Map upLoadFile(@RequestParam("upload") MultipartFile file, HttpServletRequest request) {
    Map result = new HashMap();
    String fileSizeInfo = "";
    String fileTypeInfo = "";
    try {
        System.out.println(file.getSize());
        //获取上传的文件对象以及类型和文件名,文件的name属性一定要与这里声明的文件名一致
        long fileSize = file.getSize() / 1024;
        // 若文件大于5M,则不予解析
        if (fileSize > 1024 * 5) {
            fileSizeInfo = "上传文件大于5M";
            throw new Exception("上传文件大于5M");
        }
        String fileType = getExtensionName(file.getOriginalFilename().toLowerCase());
        if (!isFileType(fileType)) {
            fileTypeInfo = "文件类型不正确";
            throw new Exception("请上传正确的文件类型!");
        }
        String uploadFileName = file.getOriginalFilename();
        String GUID = wtfkService.upLoadFile(file, uploadFileName, fileType, request);
        result.put("success", true);
        result.put("GUID", GUID);
        result.put("fileName", uploadFileName);
    } catch (Exception e) {
        e.printStackTrace();
        result.put("success", false);
    } finally {
        return result;
    }
}




  public String upLoadFile(MultipartFile localFile, String fileName, String fileType, HttpServletRequest request) throws Exception {
        String dirName = "uploadFile/cpjg/wtfk/";
        int index = fileName.lastIndexOf(".");
        String lastName = fileName.substring(index);
        // 获取随机生成的32位随机码
        localFile.getSize();
        String GUID = UUID.randomUUID().toString().replace("-", "");
        String GUIDName = GUID + lastName;
        String filePath = getSavePath(dirName, request) + GUIDName;
        String savePath = "/" + dirName + GUIDName;
        //将临时上传的文件插入临时附件表
        File targetFile = new File(filePath);
        BufferedOutputStream out = new BufferedOutputStream(
                new FileOutputStream(new File(filePath)));
        out.write(localFile.getBytes());
        out.flush();
        out.close();
        wtfkDao.updateFile(GUID, fileName, savePath, fileType);

        return GUID;
    }

使用struts2进行开发:

通过注入的File文件对象接受文件对象并且获取上传的文件对象以及类型和文件名,文件的name属性一定要与这里声明的文件对象名一致,File对象中也封装了一些获取例如文件名的工具方法可供调用。

//上传的文件
private File upload;
//文件类型
private String uploadContentType;
//文件名称
private String uploadFileName;
/**
 * 附件上传
 */
public void upLoadFile() {
    JSONObject result = new JSONObject();
    String fileSizeInfo = "";
    String fileTypeInfo = "";
    try {
        HttpServletRequest request = ServletActionContext.getRequest();
        if (!isCanUseSys(request.getSession(), 1000)) {
            throw new Exception("操作过于频繁!");
        }
        //获取上传的文件对象以及类型和文件名,文件的name属性一定要与这里声明的文件名一致
        File file = getUpload();
        long fileSize = wtfkService.getFileSize(file) / 1024;
        // 若文件大于5M,则不予解析
        if (fileSize > 1024 * 5) {
            fileSizeInfo = "上传文件大于5M";
            throw new Exception("上传文件大于5M");
        }
        String fileType = FileUtil.getExtensionName(getUploadFileName()).toLowerCase();
        if (!isFileType(fileType)) {
            fileTypeInfo = "文件类型不正确";
            throw new Exception("请上传正确的文件类型!");
        }
        String uploadFileName = getUploadFileName();
        String GUID = wtfkService.upLoadFile(file, uploadFileName, fileType);
        result.put("success", true);
        result.put("GUID", GUID);
        result.put("fileName", uploadFileName);
        result.put("message", "文件上传成功!");
    } catch (Exception e) {
        e.printStackTrace();
        result.put("success", false);
        result.put("message", LogTool.getExceptionMessage(e) + ',' + fileSizeInfo + fileTypeInfo);
    } finally {
        responseToWeb(result.toString());
    }
}

 /**
     * 附件上传功能
     *
     * @return 文件GUID
     * @throws Exception
     */
    public String upLoadFile(File localFile, String fileName, String fileType) throws Exception {
        String dirName = "uploadFile/cpjg/wtfk/";
        int index = fileName.lastIndexOf(".");
        String lastName = fileName.substring(index);
        // 获取随机生成的32位随机码
        getFileSize(localFile);
        String GUID = UUID.randomUUID().toString().replace("-", "");
        String GUIDName = GUID + lastName;
        String filePath = getSavePath(dirName) + GUIDName;
        String savePath = "/" + dirName + GUIDName;
        //将临时上传的文件插入临时附件表
        String sql = " INSERT INTO BDA_CP_T_SYS_WTFK_UPLOAD VALUES(?,?,?,TO_CHAR(SYSDATE,'YYYY/MM/DD HH24:MI:SS'),?) ";
        File targetFile = new File(filePath);
        FileUtil.copyFile(localFile, targetFile);
        bgdDataSource.updateBySql(sql, new Object[]{GUID, fileName, savePath, fileType});
        return GUID;
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值