springmvc实现文件上传

Springmvc实现文件上传

一.页面css

var disBill=0;
    function uploadFileContract(formId, selectedFile, businessTable, billId, modelName) {
        billId = disBill;//得到上传的文件ID  //表明进口报关
        modelName = "CustomsDeclareBill";
        logisticsUploadFile(formId, selectedFile, businessTable, billId, modelName);
    }

    function logisticsUploadFile(formId, selectedFile, businessTable, billId, modelName) {

        $Form = $("#" + formId);

        //根据上传的文件路径取得文件名称
        str = $('#' + selectedFile).val();
        var fileType;

        if (str == '') {
            callAlert('请先选择要上传的文件');
        }
        if(!(/(?:jpg|png|txt|xls|pdf|xlsx|doc|docx|rar|zip|html)$/i.test(str))) {
            callAlert("上传文件类型非法!");
            return;
        }
        else {
            if((/(?:jpg)$/i.test(str))){fileType='jpg'}
            if((/(?:png)$/i.test(str))){fileType='png'}
            if((/(?:txt)$/i.test(str))){fileType='txt'}
            if((/(?:xls)$/i.test(str))){fileType='xls'}
            if((/(?:doc)$/i.test(str))){fileType='doc'}
            if((/(?:docx)$/i.test(str))){fileType='docx'}
            if((/(?:rar)$/i.test(str))){fileType='rar'}
            if((/(?:zip)$/i.test(str))){fileType='zip'}
            if((/(?:xlsx)$/i.test(str))){fileType='xlsx'}
            if((/(?:pdf)$/i.test(str))){fileType='pdf'}
            if((/(?:html)$/i.test(str))){fileType='html'}
            var arr = str.split('\\');                      //注split能够用字符或字符串分割
            var fileName = arr[arr.length - 1];             //这就是要取得的文件名称
            // fileName = encodeURI(encodeURI(fileName));
            // fileType = encodeURI(encodeURI(fileType));

            var BillId=$("#billIdRecord").val();
            var formURL = getContextPath() + 'customsDeclareBill/upload.do?BillId='+BillId+'&fileType='+fileType+'&modelName='+modelName;
            var form = document.getElementById(formId);
            var formData = new FormData(form);
            $.ajax({
                url: formURL,
                type: 'POST',
                data: formData,
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function (res) {
                    callSuccess("成功!!");
                    customsGoods_table.ajax.reload();
                    customsGoods_table2.ajax.reload();
                    $('#importBillModal').modal('hide');

                },
                error: function () {
                    callSuccess("失败!!!");
                    customsGoods_table.ajax.reload();
                    customsGoods_table2.ajax.reload();
                }
            })

        }
    }复制代码

二.Controller控制器html

@RequestMapping(value = "/upload.do", method = { RequestMethod.POST })
    public @ResponseBody Object upload(HttpServletRequest request)
            throws IllegalStateException, IOException, FileUploadException {
        RequestResultVO rr = new RequestResultVO();

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());

        // 判断是否有多文件上传,即屡次请求
        if (multipartResolver.isMultipart(request)) {
            try {
                // 转成多部分的request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 取得多文件的文件名
                Iterator iter = multiRequest.getFileNames();
                while (iter.hasNext()) {
                    // 取得上传文件
                    MultipartFile f = multiRequest.getFile(iter.next()
                            .toString());
                    if (f != null) {
                        // 取得文件名称
                        String fileName = f.getOriginalFilename();
                        Long fileSize = f.getSize();
                        String fileType  = request.getParameter("fileType");//获取文件类型

                        if (fileName.trim() != "") {
                            String modelName=request.getParameter("modelName");
                            //String basepath = filepath+File.separator+modelName+File.separator+DateUtil.format(new Date(), "yyyyMMdd")+File.separator;
                            String basepath=servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("SeawinWebappBase"))+"/seawin-uploadfile/"+modelName+"/";
                            FileUtil.mkDirs(basepath);// 建立文件夹

                            String newFileName =UUID.randomUUID().toString().replace("-","")+"."+FilenameUtils.getExtension(fileName);
                            File localFile = new File(basepath+File.separator+ fileName);
                            int i = 1;
                            newFileName = fileName;
                            while(localFile.exists()){
                                if(fileName.indexOf(".") != -1){
                                    newFileName = fileName.substring(0, fileName.indexOf(".")) +"-"+i+fileName.substring(fileName.indexOf("."));
                                }else{
                                    newFileName = fileName +"-"+i;
                                }
                                i++;
                                localFile = new File(basepath+File.separator+newFileName);
                            }
                            f.transferTo(localFile); // 保存到电脑当前目录下

                            //获取端口号
                            String outPath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
                            //上传文件的文件夹名为:文件夹名+模块名+文件名
                            String fileUrl=outPath +"/seawin-uploadfile/"+modelName+"/"+ newFileName;

                            String message = "";// 0表明上传成功,1表明上传失败
                            if (!f.isEmpty() && f != null) {
                                message = "0";
                            } else {
                                message = "1";
                            }

                            }

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                rr.setContent(1, "上传失败", null);
                return rr;
            }

        }

        return rr;

    }复制代码

三.springmvc对上传文件的配置web

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:websocket="http://www.springframework.org/schema/websocket"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">


    <!-- 扫描上下文 -->
    <context:component-scan base-package="com.seawin.webapp.base.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.sale.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.base.mobileweb" />
    <context:component-scan base-package="com.seawin.webapp.freight.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.customs.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.workflow.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.shipping.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.air.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.logistics.controller.pcweb" />
    <context:component-scan base-package="com.seawin.webapp.account.controller.pcweb" />

    <!--视图解析器-->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/"
        p:suffix=".html" />


    <!--注解 -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    </bean>

    <!--json转换器RequestMappingHandlerAdapter -->
    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>  
                <bean
                    class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/html;charset=UTF-8</value>
                            <value>application/json;charset=UTF-8</value>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>


    <bean id="multipartResolver" class="com.seawin.webapp.base.mulipart.MyMultipartResolver">
        <!-- url中带有excludeUrls的http请求就不会被multipartResolver先解析 -->

                <!--手动配置的全部上传文件接口-->
                <property name="excludeUrls"
                    value="/uploader/uploadFile.do,/saleFile/uploader.do, /freightAttachment/uploadFile.do,/user/uploader.do, /logisticsAttachment/uploader.do,/CustomsDeclareBill/upload.do,/ShippingBill/upload.do" />
                <!--上传文件的最大值-->
                <property name="maxUploadSize" value="104857600"></property>
                <!--上传文件的编码-->
                <property name="defaultEncoding" value="utf-8"></property>
    </bean>

    <!-- 静态文件映射 -->
    <mvc:resources location="/" mapping="/**/*.html" />
    <mvc:resources location="/" mapping="/**/*.js" />
    <mvc:resources location="/" mapping="/**/*.css" />
    <mvc:resources location="/" mapping="/**/*.png" />
    <mvc:resources location="/" mapping="/**/*.gif" />

    <!-- 文件上传 -->
    <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
        设置上传文件的最大尺寸为5MB <property name="maxUploadSize"> <value>5242880</value> </property> 
        </bean> -->


</beans>复制代码

四.拓展
一、MultipartFile类经常使用的一些方法:ajax

String getContentType()//获取文件MIME类型
InputStream getInputStream()//获取文件流
String getName() //获取表单中文件组件的名字
String getOriginalFilename() //获取上传文件的原名
long getSize()  //获取文件的字节大小,单位byte
boolean isEmpty() //是否为空
void transferTo(File dest)复制代码

五:CommonsMultipartResolver的属性解析spring

defaultEncoding:表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-8859-1。当request本身指明了它的编码格式的时候就会忽略这里指定的defaultEncoding。
uploadTempDir:设置上传文件时的临时目录,默认是Servlet容器的临时目录。
maxUploadSize:设置容许上传的总的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。
maxUploadSizePerFile:跟maxUploadSize差很少,不过maxUploadSizePerFile是限制每一个上传文件的大小,而maxUploadSize是限制总的上传文件大小。
maxInMemorySize:设置在文件上传时容许写到内存中的最大值,以字节为单位计算,默认是10240。
resolveLazily:为true时,启用推迟文件解析,以便在UploadAction中捕获文件大小异常。复制代码

六.注意
1.有时候上传出错,是由于咱们在配置文件中限制了上传文件的大小,你能够不加这个限制,但我的建议这个限制最好仍是加上,具体文件大小限制请根据公司项目状况而定。
2.SpringMVC中使用MultipartFile接收上传文件须要依赖两个jar包,分别是:commons-fileupload-1.3.3.jar、commons-io-2.5.jar。json

相关文章
相关标签/搜索