美文网首页ssm
SpringMVC 上传文件<8>

SpringMVC 上传文件<8>

作者: 天空在微笑 | 来源:发表于2017-08-17 23:52 被阅读10次

    1.在spring配置文件中添加

      <!-- 不使用commons 上传包配置 -->
        <bean id="multipartResolver"
              class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    
            <property name="defaultEncoding" value="UTF-8" />
            <property name="maxUploadSize" value="5400000" />
            <property name="uploadTempDir" value="image" />
        </bean>
    
    1. Html5FileUploadController.java
    package com.company.combine.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    
    import com.company.combine.model.Product;
    import com.company.combine.model.UploadFile;
    import org.apache.commons.logging.Log;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.multipart.MultipartFile;
    
    
    @Controller
    public class Html5FileUploadController {
    
        private static final Log logger = org.apache.commons.logging.LogFactory.getLog(Html5FileUploadController.class);
    
        @RequestMapping(value = "/html5")
        public String inputProduct(Model model) {
            System.out.println("----------inputProduct------------:");
            model.addAttribute("product", new Product());
            return "html5";
        }
    
        @RequestMapping(value = "/file_upload", method = RequestMethod.POST)
        public void saveFile(HttpServletRequest httpServletRequest, @ModelAttribute UploadFile uploadFile,
                BindingResult bindingResult, Model model)  {
            System.out.println("----------saveFile------------:");
            MultipartFile multipartFile = uploadFile.getMultipartFile();
            
            String fileName = multipartFile.getOriginalFilename();
    //      String fileNames =fileName.substring(fileName.lastIndexOf("\\"));
            
            // File imageFile = new
            // File(httpServletRequest.getContextPath()+"/image",fileName);
            File imageFile = new File(httpServletRequest.getServletContext().getRealPath("/image"),fileName);
    
            String path = httpServletRequest.getServletContext().getRealPath("/image");
            if (!new File(path).exists()) {
                new File(path).mkdir();
            }
            System.out.println("fileName:"+fileName);
            System.out.println("multipartFile.getName():"+multipartFile.getName());
            System.out.println("path:"+path);
            System.out.println("imageFile.getAbsolutePath():"+imageFile.getAbsolutePath());
            
            try {
                multipartFile.transferTo(imageFile);
    //          model.addAttribute("image", imageFile.getAbsolutePath().toString());
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    

    3.UploadFile.java

    package com.company.combine.model;
    
    import org.springframework.web.multipart.MultipartFile;
    
    public class UploadFile {
        public MultipartFile getMultipartFile() {
            return multipartFile;
        }
    
        public void setMultipartFile(MultipartFile multipartFile) {
            this.multipartFile = multipartFile;
        }
    
        private MultipartFile multipartFile;
    }
    

    4.html5.jsp

    <%@ page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="GB2312"%>
    <!DOCTYPE html >
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
        var totalFileLength,totalUploaded,fileCount,filesUploaded;
        
        function debug(s){
            var debug = document.getElementById('debug');
            if(debug){
                debug.innerHTML = debug.innerHTML+'</br>'+s;
            }
        }
        
        function onUploadComplete(e){
            totalUploaded += document.getElementById('files').files[filesUploaded].size;
            filesUploaded++;
            debug('complete'+filesUploaded+'of'+fileCount);
            debug('totalUploaded:'+totalUploaded);
            debug('filesUploaded:'+filesUploaded);
            if(filesUploaded < fileCount){
                uploadNext();
            }else{
                var bar = document.getElementById('bar');
                bar.style.width = '100%';
                bar.innerHTML = '100% complete';
                alert('Finished uploaded file(s))');
            }
        }
        
        function onFileSelect(e){
            var files = e.target.files;
            var output = [];
            fileCount = files.length;
            debug('fileCount:'+fileCount);
            totalFileLength = 0;
            
            for(var i=0;i<fileCount;i++){
                var file = files[i];
                output.push(file.name,'(',file.size,'bytes,',file.lastModifiedDate.toLocaleDateString(),')');
                output.push('<br/>');
                debug('add'+file.size);
                totalFileLength += file.size;
                document.getElementById('selectedFiles').innerHTML = output.join('');
                debug('totalFileLength:'+totalFileLength);
                document.getElementById('selectedFiles').innerHTML = output.join('');
                debug('totalFileLength:'+totalFileLength);
            }
        }
        function onUploadProgress(s){
            if(e.lengthComputable){
                var percentComplete = parseInt((e.loaded + totalUploaded)*100/totalFileLength);
                var bar = document.getElementById('bar');
                bar.style.width = percentComplete + '%';
                bar.innerHTML = percentComplete + '%complete';
            }else{
                debug('unable to complete');
            }
        }
        
        function onUploadFailed(e){
            alert("Error uploading file");
        }
        
        function uploadNext(){
            var xhr = new XMLHttpRequest();
            var fd = new FormData();
            var file = document.getElementById('files').files[filesUploaded];
            fd.append("multipartFile",file);
            xhr.upload.addEventListener("progress",onUploadProgress,false);
            xhr.addEventListener("load",onUploadComplete,false);
            xhr.addEventListener("error",onUploadFailed,false);
            xhr.open("post","file_upload");
            debug('uploading'+file.name);
            xhr.send(fd);
        }
        function startUpload(){
            totalUploaded = filesUploaded = 0;
            uploadNext();
        }
        
        window.onload = function(){
            document.getElementById('files').addEventListener('change',onFileSelect,false);
            document.getElementById('uploadedButton').addEventListener('click',startUpload,false);
        }
    </script>
    <title>登录</title>
    </head>
    <body>
    <h1>Multiple file uploads with progress bar</h1>
    <div id='progressBar' style='height:20px;border:2px solid green'></div>
    <div id='bar' style='height:100%;background:#33dd33;width:0%'>
    </div>
    
        <form >
            <input id="files"  type="file"  multiple="multiple"/><br>
            <output id='selectedFiles'></output>
            <input id="uploadedButton" type="button" value="Upload"/><br>
        </form>
        <div id='debug' style='height:100px;border:2px solid green;overflow:auto'>
        </div>
    </body>
    </html>
    

    相关文章

      网友评论

        本文标题:SpringMVC 上传文件<8>

        本文链接:https://www.haomeiwen.com/subject/obkorxtx.html