bootstrap upload 文件上传的实现过程

前端jsp页面

<body>
    <div class="htmleaf-container" style="width:400px;height:300px;  ">
        <div class="container kv-main">
            <form enctype="multipart/form-data">
                <label>简体中文</label> <input id="file-zh" name="files" type="file"
                    multiple>
                <p class="help-block">支持jpg、jpeg、png、gif格式,大小不超过2.0M</p>
            </form>
            <hr>
            <br>
        </div>
    </div>
</body>

js部分

$(function () {
         //0.初始化fileinput
         var oFileInput = new FileInput();
         oFileInput.Init("file-zh", "<%=basePath%>user/uploadImage.do");
    });

    //初始化fileinput
    var FileInput = function () {
     var oFile = new Object();

     //初始化fileinput控件(第一次初始化)
     oFile.Init = function(ctrlName, uploadUrl) {
     var control = $('#' + ctrlName);

     //初始化上传控件的样式
     control.fileinput({
     language: 'zh', //设置语言
     uploadUrl: uploadUrl, //上传的地址
     allowedFileExtensions: ['jpg', 'gif', 'png'],//接收的文件后缀
     showUpload: true, //是否显示上传按钮
     showCaption: false,//是否显示标题
     browseClass: "btn btn-primary", //按钮样式 
     //dropZoneEnabled: false,//是否显示拖拽区域
     //minImageWidth: 50, //图片的最小宽度
     //minImageHeight: 50,//图片的最小高度
     //maxImageWidth: 1000,//图片的最大宽度
     //maxImageHeight: 1000,//图片的最大高度
     //maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
     //minFileCount: 0,
     maxFileCount: 10, //表示允许同时上传的最大文件个数
     enctype: 'multipart/form-data',
     validateInitialCount:true,
     previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
     msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
     });

     //导入文件上传完成之后的事件
    $('#file-zh').on('fileuploaded', function(event, data, previewId, index) {
        var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
        console.log(response);//打印出返回的json
        console.log(response.paths);//打印出路径
        });
    }
     return oFile;
    };

controller的实现部分

/**
     * 
     * @Title: uploadFj
     * @Description: TODO(上传附件)
     * @param request
     */
    @RequestMapping(value = "/uploadFj")
    public void uploadFj(HttpServletRequest request,
            HttpServletResponse response) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        List<UploadFile> fileList = UploadUtil.getUploadFiles(multiRequest,
                ContextUtil.setPath());
        Map<String, Object> map = new HashMap<String, Object>();
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            for (UploadFile file : fileList) {
                System.out.println("上传文件有:" + file);
            }

            map.put("message", "success");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("meaasge", "failed");
        }
        out.print(JSONObject.fromObject(map));
    }

upload工具类UploadUtil

public static List<UploadFile> getUploadFiles(
            MultipartHttpServletRequest multipartHttpServletRequest, String Path) {
        List<MultipartFile> files = multipartHttpServletRequest
                .getFiles("files");
        List<UploadFile> fileList = new ArrayList<UploadFile>();
        for (MultipartFile file : files) {
            // 取得上传文件
            String fileName = file.getOriginalFilename();
            Long fileSize = file.getSize();
            if (null != fileName && !"".equals(fileName)) {
                try {
                    // 创建文件要保存的路径
                    File uploadFile = new File(Path);
                    if (!uploadFile.exists() || null == uploadFile) {
                        uploadFile.mkdirs();
                    }
                    // 获取文件类型
                    String fileType = fileName.substring(
                            fileName.lastIndexOf(".") + 1, fileName.length());
                    String id = UUID.randomUUID().toString();
                    String targetName = id + "." + fileType;
                    // 文件真实存放路径
                    String filePath = uploadFile.getPath() + File.separator
                            + targetName;
                    // 保存文件
                    file.transferTo(new File(filePath));
                    // 初始化上传文件
                    UploadFile up = new UploadFile(id, fileName, fileType,
                            fileSize + "", filePath);
                    fileList.add(up);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return fileList;
    }

文件实体类

/**
 * 上传文件实体类
 * 
 * @author 
 * 
 */
public class UploadFile implements Serializable {

    private static final long serialVersionUID = -5077361410541860143L;
    private String id;
    private String fileName;
    private String fileType;
    private String fileSize;
    private String filePath;

    public UploadFile() {

    }

    public UploadFile(String id, String fileName, String fileType,
            String fileSize, String filePath) {
        this.id = id;
        this.fileName = fileName;
        this.fileType = fileType;
        this.fileSize = fileSize;
        this.filePath = filePath;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public String getFileSize() {
        return fileSize;
    }

    public void setFileSize(String fileSize) {
        this.fileSize = fileSize;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    @Override
    public String toString() {
        return "UploadFile [id=" + id + ", fileName=" + fileName
                + ", fileType=" + fileType + ", fileSize=" + fileSize
                + ", filePath=" + filePath + "]";
    }

页面效果图
这里写图片描述

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值