1. 程式人生 > >bootstrap upload 檔案上傳的實現過程

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 + "]";
    }

頁面效果圖
這裡寫圖片描述