小夜埙
路很长,要耐心,慢慢走!

之前整理过SSM的文件上传,这次直接用代码了。
前台页面和js

    //form表单
    <form id= "uploadForm" enctype="multipart/form-data">
         <input type="file" name="uploadfile" id="uploadfile"/>
         <input type="button" value="上传" onclick="doUpload()" class="btn btn-success fileinput-button"/>
         <input type="hidden" name="pictureCertificate" id="pictureCertificate" value="">
   </form>


//js代码
 function doUpload() {
        /*var formData = new FormData();
        formData.append("uploadfile", document.getElementById("uploadfile").files[0]);*/
        var formData = document.getElementById("uploadfile").files[0]; // js 获取文件对象
        if (typeof (formData) == "undefined" || formData.size <= 0) {
            alert("请选择图片!");
            return;
        } else {
            var formData = new FormData();
            formData.append("uploadfile", document.getElementById("uploadfile").files[0]);
        }
        //var formData = new FormData($( "#uploadForm" )[0]);
        //alert(formData);
        $.ajax({
            url: '<%=basePath%>/creditBill/fileUpload.do' ,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (returndata) {
                //$("#pictureCertificate").val(returndata);
                if(returndata.code == "3") {
                    alert("上传图片格式不正确!");
                } else if (returndata.code == "0") {
                    alert("上传文件不得大于500k!");
                } else if (returndata.code == "404" || returndata.code == "1") {
                    alert("上传凭证失败!");
                } else {
                    alert("上传凭证成功!");
                    $("#pictureCertificate").val(returndata.path);
                }

            },
            error: function (returndata) {
                alert("上传凭证失败!");
            }
        });
    }

后台代码

/**
     * 图片上传
     * @param
     * @param uploadfile
     * @param request
     * @return
     */
    @RequestMapping("/fileUpload")
    @ResponseBody
    public UploadResult handleFormUpload(@RequestParam("uploadfile") List<MultipartFile> uploadfile,
                                   HttpServletRequest request) {
        UploadResult result = new UploadResult();

        //判断上传文件是否存在
        if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
            //循环输出上传的文件
            for (MultipartFile file : uploadfile) {
                //获取上传文件的原始名称
                String oringinalFilename = file.getOriginalFilename();
                //获取源文件名后缀
                String prefixName = FilenameUtils.getExtension(oringinalFilename);

                int fileSize = 500000;
                //图片限制在500k以内
                if(file.getSize() > fileSize) {
                    result.setCode("0");
                    return result;
                } else if(prefixName.equalsIgnoreCase("jpg")
                        || prefixName.equalsIgnoreCase("png")
                        || prefixName.equalsIgnoreCase("jpeg")
                        || prefixName.equalsIgnoreCase("pneg")) {
                    //设置上传文件的保存地址目录
                    String dirPath = request.getSession().getServletContext().getRealPath("/fileupload/");
                    //区分windows和linux的\ 和 /
                    //String dirPath = "E:"+System.getProperty("file.separator")+"uploadfile" + System.getProperty("file.separator");
                    //String dirPath = System.getProperty("file.separator") + "usr" + System.getProperty("file.separator") + "local"
                           // + System.getProperty("file.separator")+"imgbak"+System.getProperty("file.separator");
                    System.out.println("dirpath==" + dirPath);
                    File filePath = new File(dirPath);
                    //如果文件地址不存在 则创建目录
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    //使用时间格式重新命名
                    String newFilename = VeDate.getNo(4) + "."+prefixName;
                    System.out.println("/fileupload/" + newFilename);
                    try {
                        //使用MultipartFilr接口的方法完成文件上传到指定位置
                        file.transferTo(new File(dirPath + newFilename));
                        String filepath = "/fileupload/" + newFilename;
                        result.setPath(filepath);
                    } catch (IOException e) {
                        result.setCode("1");
                        return result;
                    }
                } else {
                    System.out.println("上传图片格式不正确");
                    result.setCode("3");
                    return result;
                }
            }
            //上传成功
            return result;
        } else {
            result.setCode("404");
            return result;
        }
    }

UploadResult 实体类

/**
 * @author 
 * @version V1.0
 * @Description:
 * @date 2018/1/23 17:03
 */
public class UploadResult {

    /**
     * 错误代码
     */
    private String code;
    /**
     * 上传文件路径
     */
    private String path;
    //……
}

小结

工作总结,都是文件上传,只是情况不同,本来想用前端文件上传的框架,结果半天都不行,就用了Ajax的上传方式,结果还好。

posted on 2018-01-25 11:39  小夜埙  阅读(564)  评论(0编辑  收藏  举报