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

相關文章
相關標籤/搜索