zoukankan      html  css  js  c++  java
  • spring mvc框架+ ajax实现 文件上传

    1.前端页面,通过form表单提交,必须设置

    enctype="multipart/form-data"  代表form表单在发送到服务器时候编码方式是二进制类型,一般用于图片、mp3、文件
    <form method="get" action="" class="form-horizontal" role="form" id="form_data" onsubmit="return check_form()" style="margin: 20px;" enctype="multipart/form-data">
                        <div class="modal fade" id="addModal" tabindex="-1" role="dialog"  aria-labelledby="myModalLabel" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <button type="button" class="close" data-dismiss="modal"  aria-hidden="true">&times;</button>
                                        <h4 class="modal-title" id="myModalLabel">配置信息</h4>
                                    </div>
                                    <div class="modal-body">
                                        <form class="form-horizontal" role="form">
                                            <div class="form-group">
                                                <label for="projectid" class="col-sm-3 control-label">项目名称</label>
                                                <div class="col-sm-9">
                                                    <select class="form-control" name="projectid" id="projectid">
                                                        <c:forEach var="p" items="${projects }">
                                                            <option value="${p.projectid}">${p.projectname}</option>
                                                        </c:forEach>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="form-group">
                                                <label for="apppackage" class="col-sm-3 control-label">app包名</label>
                                                <div class="col-sm-9">
                                                    <input type="text" class="form-control" name="apppackage" id="apppackage" placeholder="app包名">
                                                </div>
                                            </div>
    
                                            <div class="form-group">
                                                <%--@declare id="files"--%>
                                                    <label for="files" class="col-sm-3 control-label">上传apk</label>
                                                <div class="col-sm-9">
                                                    <input type="file" class="form-control" id="apkupload" name="files">
                                                </div>
                                            </div>
    
                                            <div class="form-group">
                                                <label for="remark" class="col-sm-3 control-label">备注</label>
                                                <div class="col-sm-9">
                                                    <textarea class="form-control" name="remark" id="remark"  placeholder="备注"></textarea>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-default"   data-dismiss="modal" id="close">关闭</button>
                                        <button type="submit" class="btn btn-primary" disabled="disabled">提交</button>
                                        &nbsp;&nbsp;&nbsp;&nbsp;<span id="tip"> </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>        

    2. ajax请求 

    注意:contentType要设置为false,
    当在form 标签中设置了enctype = “multipart/form-data”后,请求中的 contentType 会默认为 multipart/form-data 。
    而ajax中contentType设置为false是为了避免 JQuery 对其操作,从而失去分界符,而使服务器不能正常解析文件(文件是需要分隔符的,比如文件内容和文本内容之间就是用分割符分割)
    补充:
    async 默认是true,即为异步方式,$.Ajax执行后,会继续执行ajax后面的脚本,直到服务器端返回数据后,触发$.Ajax里的success方法,这时候执行的是两个线程。
          若为false,则所有的请求均为同步请求,用户必须等待请求完成才能执行其他操作。
    // 提交表单
        function check_form(){
            // var form_data = $('#form_data').serialize();
            var formData = new FormData($( "#form_data" )[0]);
            // 异步提交数据到action页面
            $.ajax({
                    url: "configadd.do",
                    data:formData,
                    type: "post",
                    // dataType : "json",//返回数据的类型
                    async: false,
                    cache: false,
                    contentType: false,//发送数据的类型
                    processData: false,
                    beforeSend:function(){
                        $("#tip").html("<span style='color:blue'>正在处理...</span>");
                        return true;
                    },
                    success:function(data, status){
                        console.log("请求成功返回数据============="+status);
                        if(status == "success"){
                            alert("添加成功-------")
                            $("#tip").html("<span style='color:blueviolet'>恭喜,添加配置成功!</span>");
                            setTimeout(fn, 1000);
                            function  fn(){
                                document.getElementById("close").click();
                            }
                            toastr.success(data.ms);
                        }else{
                            $("#tip").html("<span style='color:red'>失败,请重试</span>");
                            toastr.info(data.ms);
                        }
                    },
                    error:function(){
                        toastr.error('请求出错!');
                    },
                    complete:function(){
                        $('#addModal').hide();
                    }
                });
            return false;
        }
    3.Spring配置文件applicationContext.xml   中增加上传文件的配置
        <!--文件上传使用, 配置multipartResolver,id名为约定好的 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- 配置文件(每次上传的所有文件总大小)大小,单位为b, 1024000表示1000kb  -->
            <property name="maxUploadSize" value="102400000" />
        </bean>
        <!--PropertiesFactoryBean对properties文件可用 ,可以用来注入properties配置文件的信息 -->
        <bean id="uploadProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
            <property name="location" value="classpath:upload.properties"></property>
        </bean>
    
    

    4.文件上传的工具类

    (一)上传到服务器

    @Component(value="fileUploadUtils")
    public class FileUploadUtil {
        @Value("#{uploadProperties.path}")
        private String path;
        private String getExtName(MultipartFile file){
            return FilenameUtils.getExtension(file.getOriginalFilename());
        }
        private String createNewName(MultipartFile file){
            return UUID.randomUUID().toString()+"."+getExtName(file);
        }
        public String uploadFile(MultipartFile file){
            try {
                String newName=createNewName(file);
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path,newName ));
                return newName;
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    (二)通过ftp远程上传

    public class FtpUtil {
        /**
         * Description: 向FTP服务器上传文件
         * @param host FTP服务器hostname
         * @param port FTP服务器端口
         * @param username FTP登录账号
         * @param password FTP登录密码
         * @param basePath FTP服务器基础目录
         * @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
         * @param filename 上传到FTP服务器上的文件名
         * @param input 输入流
         * @return 成功返回true,否则返回false
         */
        public static boolean uploadFile(String host, int port, String username, String password, String basePath,
                                         String filePath, String filename, InputStream input) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);// 连接FTP服务器
                // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftp.login(username, password);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                //切换到上传目录
                if (!ftp.changeWorkingDirectory(basePath+filePath)) {
                    //如果目录不存在创建目录
                    String[] dirs = filePath.split("/");
                    String tempPath = basePath;
                    for (String dir : dirs) {
                        if (null == dir || "".equals(dir)) continue;
                        tempPath += "/" + dir;
                        if (!ftp.changeWorkingDirectory(tempPath)) {
                            if (!ftp.makeDirectory(tempPath)) {
                                return result;
                            } else {
                                ftp.changeWorkingDirectory(tempPath);
                            }
                        }
                    }
                }
                //设置上传文件的类型为二进制类型
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                //上传文件
                if (!ftp.storeFile(filename, input)) {
                    return result;
                }
                input.close();
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
    
        /**
         * Description: 从FTP服务器下载文件
         * @param host FTP服务器hostname
         * @param port FTP服务器端口
         * @param username FTP登录账号
         * @param password FTP登录密码
         * @param remotePath FTP服务器上的相对路径
         * @param fileName 要下载的文件名
         * @param localPath 下载后保存到本地的路径
         * @return
         */
        public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
                                           String fileName, String localPath) {
            boolean result = false;
            FTPClient ftp = new FTPClient();
            try {
                int reply;
                ftp.connect(host, port);
                // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
                ftp.login(username, password);// 登录
                reply = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftp.disconnect();
                    return result;
                }
                ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
                FTPFile[] fs = ftp.listFiles();
                for (FTPFile ff : fs) {
                    if (ff.getName().equals(fileName)) {
                        File localFile = new File(localPath + "/" + ff.getName());
    
                        OutputStream is = new FileOutputStream(localFile);
                        ftp.retrieveFile(ff.getName(), is);
                        is.close();
                    }
                }
    
                ftp.logout();
                result = true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                    }
                }
            }
            return result;
        }
        public static void main(String[] args) {
            try {
                FileInputStream in=new FileInputStream(new File("D:\temp\image\gaigeming.jpg"));
                boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);
                System.out.println(flag);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    5.实体AppiumConfig中增加文件类型的属性

        private MultipartFile[] files;

    6.控制层controller中,实现上传功能,保存上传文件的路径到实体

                        MultipartFile[] files = AppiumConfig.getFiles();
    //                    System.out.println("真实路径:" + application.getRealPath("/"));
                        String path =application.getRealPath("/");
                        for (MultipartFile multipartFile : files) {
    //                        System.out.println("文件类型:" + multipartFile.getContentType());
    //                        System.out.println("文件控件名:" + multipartFile.getName());
    //                        System.out.println("文件名:" + multipartFile.getOriginalFilename());
    //                        System.out.println("文件大小:" + multipartFile.getSize());
                            try {
                                FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(application.getRealPath("/") + "upload/" + multipartFile.getOriginalFilename()));
                            } catch (IOException e) {
                                e.printStackTrace();
                            }   path +=multipartFile.getOriginalFilename();
                        }
                        AppiumConfig.setApkupload(path);
     
  • 相关阅读:
    接口隔离原则
    单一职责原则
    设计模式
    typora的快捷键构建
    typora的使用
    MapReuduce的一些情况
    Django之创建超级用户
    Tensorflow在python3.7版本的运行
    开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上,要求输出结果必须按ABC的顺序显示:ABCABC
    VM10 win7 虚拟机+VS各种版本的快照...
  • 原文地址:https://www.cnblogs.com/alasijia/p/9306143.html
Copyright © 2011-2022 走看看