1. 程式人生 > >工作總結之----IE使用ajax上傳檔案報錯,其他瀏覽器正常問題解決過程

工作總結之----IE使用ajax上傳檔案報錯,其他瀏覽器正常問題解決過程

錯誤資訊:

嚴重: Servlet.service() for servlet [springMVC] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is org.apache.commons.fileupload.FileUploadException: Stream ended unexpectedly] with root cause
org.apache.commons.fileupload.MultipartStream$MalformedStreamException: Stream ended unexpectedly
at org.apache.commons.fileupload.MultipartStream.readHeaders(MultipartStream.java:540)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.findNextItem(FileUploadBase.java:1038)
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.hasNext(FileUploadBase.java:1106)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:339)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:115)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:158)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.resolveMultipart(CommonsMultipartResolver.java:142)
at org.springframework.web.servlet.DispatcherServlet.checkMultipart(DispatcherServlet.java:1089)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:928)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:957)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:620)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2516)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2505)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

jsp頁面部分程式碼(已完成修改):

<form id="form1" method="post" enctype="multipart/form-data">
    <div class="formWrap" align="center">
        <table class="center" cellpadding="0" cellspacing="0">
            <tr>
                <td class="project_td">
                    <div
><i></i>姓名</div> </td> <td class="content_td"> <input name="userName" class="mini-textbox" required="true" value="${user.userName}"/> </td> <td colspan="2" rowspan="3"> <
div style="border: 1px solid #f2f2f2;width:100px;height: 100px;margin-right: 100px;float:right;margin-right: 70px;" id="imgyulan"> <c:if test="${user.headImgPath == null || user.headImgPath == ''}"> <img src="/app/img/150.png" alt="頭像" id="defaultHead" name="defaultHead" style="width:100%;height:100%;" > </c:if> <c:if test="${not empty user.headImgPath}"> <img src="/users/getImg?headImgPath=${user.headImgPath}" alt="頭像" id="defaultHead" name="defaultHead" style="width:100%;height:100%;"/> </c:if> </div> <input type="file" style="display: none;" id="head" name="file1"> <input type="hidden" id="fileChanged" name="fileChanged"/> </td> </tr> <tr> <td class="project_td"> <div><i></i>部門</div> </td> <td class="content_td"> <input id="organiseName" name="organiseName" class="mini-buttonedit" allowInput="false" required="true" onbuttonclick="onButtonEdit" value="${user.organiseName}" text="${user.organiseName}"> <input class="mini-hidden" id="organiseId" name="organiseId" required="true" vtype="maxLength:36;specialCharacter" value="${user.organiseId}"/> </td> </tr> <tr> <td class="project_td"> <div>辦公室電話</div> </td> <td class="content_td"> <input name="officePhoneNum" id="officePhoneNum" class="mini-textbox" value="${user.officePhoneNum}"/> </td> </tr> <tr> <td class="project_td"> <div><i></i>郵箱</div> </td> <td class="content_td"> <input name="email" class="mini-textbox" vtype="email" value="${user.email}"/> </td> <td class="project_td"> <div><i></i>聯絡電話</div> </td> <td class="content_td"> <input name="phoneNum" class="mini-textbox" required="true" vtype="int" onvalidation="onTelephoneValidation" value="${user.phoneNum}"/> </td> </tr> </table> <div class="buttonDiv"> <a class="mini-btn ok" onclick="onOk()">&nbsp;</a> <a class="mini-btn cancle" onclick="onCancel()" >&nbsp;</a> </div> </div> <input class="mini-hidden" name="userId" value="${user.userId}" id="userId"> </form>

ajax程式碼:

$.ajax({
    url: "/users/updateUser",
    type: 'post',
    data: o,
    processData: false,
    contentType: false,
    success: function (data) {
        checkSubmitFlg = true;
        if (data.code == -1) {
            mini.alert("修改失敗", "提示", onCancel);
        } else {

            mini.alert("修改成功", "提示", onCancel);
        }
    },
    error: function (data) {
        mini.alert("修改失敗", "提示", onCancel);
    }
});
java後臺服務程式碼:
 @RequestMapping(value = "/updateUser", method = RequestMethod.POST)
    @ResponseBody
public HashMap updateUser(HttpServletRequest request, HttpServletResponse response, Users users) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        String fileChanged = request.getParameter("fileChanged");
        String id = users.getUserId();
        Users oldusers = usersService.selectUsersByPrimaryKey(id);
        if ("1".equals(fileChanged)){//修改縮圖
MultipartFile multipartFile1 = multipartHttpServletRequest.getFile("file");
            HeadingImg image = new HeadingImg();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            String dateStr = sdf.format(new Date());
            Long si = multipartFile1.getSize();
            BigDecimal b = new BigDecimal(si);
            Properties properties = ConfigUtil.PROPERTIES;
            String path = properties.getProperty("imageResourcrsPath");
            path = path + "/head/" + dateStr;
            // 獲取上傳的圖片檔案
String fileName = multipartFile1.getOriginalFilename();
            File file = new File(fileName);
            if(file != null && !"".equals(file)) {
                File f = new File(path);
                if (!f.exists()) {
                    f.mkdirs();
                }
                // 防止出現重名檔案--uuid重新命名
File newFile = FileUtil.renameFile(file);
                // 伺服器存的真實名字
String newFileName = newFile.getName();

                // 伺服器路徑(路徑+真實名字)
StringBuffer newPaths = new StringBuffer(path);
                newPaths.append("/");
                newPaths.append(newFileName);
                // 路徑+真實名字
String newPath = newPaths.toString();
                // 伺服器中檔案
File targetFile = new File(path, newFileName);
                //真實圖
try {
                    multipartFile1.transferTo(targetFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }                //縮圖
String path2 = path + "/"+newFileName;
                try {
                    processUploadedFile(path2, newFileName);

                } catch (Exception e) {
                    e.printStackTrace();
                }


                String realPath = headingImgService.getImagePath(id);
                if(realPath != null && !"".equals(realPath)) {
                    String sltPath = StringUtil.getSltPath(realPath);
                    FileUtil.deleteFile(realPath);
                    FileUtil.deleteFile(sltPath);
                    image.setObjId(id);
                    image.setFileId(id);
                    image.setFileName(imageName);
                    image.setFilePath(newPath);
                    image.setFileSize(b);
                    headingImgService.updateImage(image);
                }else{
                    image.setObjId(id);
                    image.setFileId(id);
                    image.setFileName(imageName);
                    image.setFilePath(newPath);
                    image.setFileSize(b);
                    headingImgService.addImage(image);
                }
            }
        }
        oldusers.setUserName(users.getUserName());
        oldusers.setUserCode(users.getUserName());
        oldusers.setOrganiseName(users.getOrganiseName());
        oldusers.setOrganiseId(users.getOrganiseId());
        oldusers.setPosition(users.getPosition());
        oldusers.setIsSoundRemind(users.getIsSoundRemind());
        oldusers.setIsVibrateRemind(users.getIsVibrateRemind());
        oldusers.setJobNum(users.getJobNum());
        oldusers.setEmail(users.getEmail());
        oldusers.setPhoneNum(users.getPhoneNum());
        oldusers.setOfficePhoneNum(users.getOfficePhoneNum());
        int edit = usersService.updateUsers(oldusers);
        HashMap map = new HashMap();
        map.put("code", edit);
        String json = JsonUtils.encode(map);
        System.out.println(json);
        return map;
    }
解決步驟:

1.檢驗form標籤是否新增以下屬性

enctype="multipart/form-data"

2.檢驗jsp程式碼中是否存在沒有name屬性的input標籤,如果存在的話將input的name屬性加上

改為

3.如果以上兩步操作完成問題已解決,這步操作可忽略,這步操作是在form的最後新增隱藏的input或者將已有的隱藏的input元素移到最後作為最後一個元素

參考資料:

相關推薦

工作總結----IE使用ajax檔案其他瀏覽器正常問題解決過程

錯誤資訊: 嚴重: Servlet.service() for servlet [springMVC] in context with path [] threw exception [Request processing failed; nested exceptio

sshclient檔案:encountered 1 errors during the transfer解決方法

encountered 1 errors during the transfer解決方案: 1.檢視要檔案目錄許可權,當前使用者對要上傳檔案的目錄 要有rwx許可權; 2.把伺服器上同名檔案先備份在上傳; 3.如果檔案在桌面上上傳不了,將要上傳的檔案複製到其它分割槽,再上

Hadoop檔案could only be written to 0 of the 1 minReplication nodes.

報錯:org.apache.hadoop.ipc.RemoteException(java.io.IOException): File /home/navy/files/yc.txt could only be written to 0 of the 1 minReplic

解決Go檔案:找不到Boundary的問題

最近要做一個元件,即接收客戶端的請求,經過一系列的封裝,將請求傳送給真正的服務端器。可以理解為:客戶端使用Http的Request的Body儲存檔案流,將Request傳送給伺服器。遇到一個問題:傳入的是一個檔案控制代碼File,需要轉換成byte[]存到request的body中,但是發現boun

MultipartFile 動態決定是否檔案,解決檔案

controller 接收引數   用 HttpServletRequest 代替 @RequestParam()  接收引數   picFile 前臺 傳檔案的引數名字  ,   這樣 前段 傳 null  就可以

關於springboot檔案:The temporary upload location ***is not valid

  在執行springboot時 ,長時間執行後報錯 the temporary uplaod location *** is not valid  查過資料後發現是centos對‘/temp’下檔案自動清理的原因。  在springboot專案啟動後 系統會在‘/temp’目

檔案時報如下錯誤springmvc檔案org.springframework.beans.BeanInstantiationException

在用springmvc+mybatis進行專案開發時,上傳檔案拋異常.. org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web

微信小程式使用wx.uploadFile 檔案 uploadFile:fail null

問題描述: 在使用wx.uploadFile的時候,安卓手機會報錯:uploadFile:fail null。而蘋果手機則可以正常上傳 其實原因出在訪問的介面中 修改之前的程式碼片段: wx.uploadFile({ url:

FTP檔案200 PORT command successful. Consider using PASV. 553 Could not create file.

一、背景最近搭好的在雲主機上搭好了nginx環境,打算通過ftp上傳一個靜態的網頁上去test一波,然後進去了ftp,在上面put了一下,結果沒有看到想象中上傳成功的樣子,看到的是200 PORT command successful. Consider using PASV

ajax 檔案 Warning: Cannot modify header information - headers already sent in Unknown on line 0

在使用ajax更新或上傳資料的時候,return回來的卻是一堆錯誤 後來才知道原來是PHP5.6有的功能已經廢棄了,所以我需要開啟PHP.ini檔案,找到 ;always_populate_raw_post_data = -1 將前面的分號去掉 always_popula

用微軟自帶的FileUpload控制元件檔案

解決方法:在WebConfig 中 增加<system.web>     <httpRuntime useFullyQualifiedRedirectUrl="true" maxRequestLength="104857" executionTimeout=

jS Ajax 檔案"Uncaught TypeError: Illegal invocation"

ajax向後臺傳包括圖片、字串等資料的時候報錯。錯誤程式碼: jquery-3.1.1.min.js:4 Uncaught TypeError: Illegal invocation 錯誤原因:

spring Boot檔案

spring Boot版本 1.4.5  報錯原因:org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested excepti

SFTP 檔案:SFTP ERROR?Algorithm negotiation fail

專案過程中曾經遇到這樣一個錯誤:SFTP ERROR?Algorithm negotiation fail。java程式碼利用SFTP上傳客戶伺服器報錯,但是可以在Linux上上傳成功,嘗試過很多解決

使用SmartUpload檔案

今天在寫一個檔案上傳時,發現總是在upload方法時報錯,並且報了這麼個錯誤當時就很納悶了,講道理一般upload方法一般都不會報錯的,然後只能各種百度,最後發現就是因為沒有給SmartUpload這個物件設定一個字元編碼,所以它就一直報錯,解決辦法就是把我註釋的那條su.s

使用struts2的標籤其他功能正常

web.xml檔案中將struts2的filter-mapping改為下面這樣的即可。 <filter-mapping>   <filter-name>struts2</filter-name>   <url-pattern>/*</url-pattern

flask外掛系列flask_uploads檔案

前言 flask可以實現上傳檔案和下載檔案的基本功能,但如果想要健壯的功能,使用flask_uploads外掛是十分方便的。 安裝 pip install flask_uploads 基本使用 # extensions.py from flask_uploads import UploadSet f

檔案相關: The current request is not a multipart request或is a MultipartResolver configured?

1:The current request is not a multipart request    1:from中涉及到圖片上傳的就要用post提交方式。否則就會報這個錯誤。    2:第一中:在jsp頁面的<head></head>標籤裡面加上&

springboot 圖片 檔案大小的問題解決辦法

前面省略N,直接上傳然後報錯程式碼截圖:nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; n

springcloud採坑--Zuul檔案java.nio.charset.IllegalCharsetNameException: UTF-8;boundary=sqgzzmMxl1UPdIp0IAYnQgUIAr9yNewVAzKIX

報錯日誌: 2018-12-17 10:01:19,688 ERROR [io.undertow.request] (default task-3) UT005023: Exception handling request to /xxx/app/bannerMaterialManager/uploadBa