layUI框架中文件上傳先後端交互及遇到的相關問題

下面我將講述一下我在使用layUI框架中文件上傳所遇到的問題:javascript

前端jsp頁面:html

<div class="layui-form-item"> 
  <label class="layui-form-label">照片</label> 
  <div class="layui-input-block">     <!-- 上傳按鈕 -->     <button type="button" class="layui-btn" id="uploadPic"><i class="layui-icon">&#xe67c;</i>選擇圖片</button>     <br><br>     <button type="button" class="layui-btn layui-btn-warm" id="uploadPicBtn">開始上傳</button>     <!-- 隱藏的input,一個隱藏的input(用於保存文件url) -->     <input type="hidden" id="img_url" name="img" value=""/>     <!-- 預覽區域 -->     <div class="layui-upload-list">       <img class="layui-upload-img" width="100px" height="80px" id="preShow"/>       <p id="demoText"></p>     </div>   </div> </div> <div class="layui-form-item">   <label class="layui-form-label">視頻</label>     <div class="layui-input-block">     <!-- 上傳按鈕 --> <!-- <input type="file" name="file2" lay-type="video" class="layui-upload-file"> --> <button type="button" class="layui-btn" id="uploadVideo"><i class="layui-icon"></i>上傳視頻</button> <button type="button" class="layui-btn layui-btn-warm" id="uploadVideoBtn">開始上傳</button> <!-- 隱藏的input,一個隱藏的input(用於保存文件url) --> <input type="hidden" id="video_url" name="video" value=""/>   </div> </div> <script src="${basePath}/x-admin/lib/layui/layui.js" charset="utf-8"></script> <script type="text/javascript" src="${basePath}/public/js/jquery-3.3.1.min.js"></script> /* 前端文件上傳到java後端控制器 */ 
 <script>   layui.use('upload', function(){ var upload = layui.upload , $ = layui.jquery; //上傳圖片 var uploadInst = upload.render({ elem: '#uploadPic' //綁定元素 ,url: '${basePath}/ar/uploadFile' //上傳接口 [[@{/upload/img}]] ,auto: false ,bindAction: '#uploadPicBtn' ,before: function(obj){ //預讀本地文件示例,不支持ie8 obj.preview(function(index, file, result){ $('#preShow').attr('src', result); //圖片連接(base64) }); } ,done: function(res){ //若是上傳失敗 if(res.code > 0){ alert("上傳失敗"+res.data.src); return layer.msg('上傳失敗'); } //上傳成功 alert("上傳成功"+res.data.src); document.getElementById("img_url").value = res.data.src; return layer.msg('上傳成功'); } ,error: function(){ /*date_default_timezone_set("Asia/Shanghai"); //演示失敗狀態,並實現重傳 var dd=res.responseText.replace(/<\/?.+?>/g,""); var text=dd.replace(/ /g,"");//去掉全部空格 o.msg("請求上傳接口出現異常"+text), console.log(text); m(e) */ var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上傳失敗</span> <a class="layui-btn layui-btn-mini demo-reload">重試</a>'); demoText.find('.demo-reload').on('click', function(){ uploadInst.upload(); }); } }); //上傳視頻 var uploadInst =upload.render({ elem: '#uploadVideo' ,url: '${basePath }/ar/uploadFile' ,accept: 'video' //視頻 ,done: function(res){ console.log(res) //若是上傳失敗 if(res.code > 0){ alert("上傳失敗"+res.data.src); return layer.msg('上傳失敗'); } //上傳成功 alert("上傳成功"+res.data.src); /* document.getElementById("img_url").value = res.data.src; */ return layer.msg('上傳成功'); }       }); } );

java後臺控制端:前端

@Controller
@RequestMapping(value="/ar")
@MultipartConfig
public class AnalyseRepariController {
@Autowired
private AnalyseRepariService arService;
  //圖片上傳控制器
        @RequestMapping(value = "/uploadFile" , method = RequestMethod.POST) 
        @ResponseBody
        public JSONObject uploadPicture(@RequestParam("file")MultipartFile file,HttpServletRequest servletRequest) 
                        throws IOException { 
                //若是文件內容不爲空,則寫入上傳路徑 
                //String str = "";
                JSONObject res = new JSONObject();
                JSONObject resUrl = new JSONObject();
                //上傳文件路徑 
                String path = servletRequest.getServletContext().getRealPath("/uploadFile");
                
                System.out.println("文件名稱"+file.getOriginalFilename()); 
                //上傳文件名         
                String name = file.getOriginalFilename();//上傳文件的真實名稱
                String suffixName = name.substring(name.lastIndexOf("."));//獲取後綴名
                String hash = Integer.toHexString(new Random().nextInt());//自定義隨機數(字母+數字)做爲文件名
                String fileName = hash + suffixName;        
                File filepath = new File(path, fileName); 
                System.out.println("隨機數文件名稱"+filepath.getName()); 
                //判斷路徑是否存在,沒有就建立一個 
                if (!filepath.getParentFile().exists()) { 
                    filepath.getParentFile().mkdirs(); 
                    } 
                //將上傳文件保存到一個目標文檔中 
                File tempFile = new File(path + File.separator + fileName);
                file.transferTo(tempFile);
                
                resUrl.put("src", tempFile.getPath());
                res.put("code", 0);
                res.put("msg", "");
                res.put("data", resUrl);
                //str = "{\"code\": 0,\"msg\": \"上傳成功\",\"data\": {\"src\":\""+path+fileName + "\"}}";
                System.out.println("res裏面的值:");
                System.out.println(res.toString());    
                return res;
            } 
}

報「請求上傳接口異常」問題,通常的解決方法:java

 一、後臺返回到前臺的json數據一直報數據接口異常jquery

第一,檢查本身返回的json數據格式是否正常,該接口返回的相應信息(response)必須是一個標準的 JSON 格式,如:返回的數據格式是不是web

{
  "code": 0
  ,"msg": ""
  ,"data": {
    "src": "http://cdn.layui.com/123.jpg"
  }
}       

返回的數據格式是這樣的,可是仍是報數據接口異常的話
第二,msg的值必定要寫"",否則會一直報錯,本身設定的code值必定要寫0,其餘的值都是錯誤的。
二、json數據包是否配置好,我就是這樣才致使一直報錯spring

 SpringController.java中須要以下代碼:並在構建路徑中引入 這兩個jar包,才能支持json格式的生成。
json

jackson-core-asl-1.9.11.jar後端

jackson-mapper-asl-1.9.11.jar
先下載這兩個jar包,並加到項目的WebContent\WEB-INF\lib目錄下,而後在編輯器目錄中右擊選擇Web App Libraries中的Configure Build Path...引入項目中放入的兩個jar包。
瀏覽器

在springmvc.xml中須要配置以下信息:

    <!-- 註解映射器 -->
<!-- 必定要配置這個,不然layui框架中文件上傳會報請求上傳接口異常,JACKSON包,讓Spring MVC支持JSON視圖的解析以及返回JSON數據進行呈現 --> <!--引入json支持,josn轉換器配置 --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <!-- json轉換器 --> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
</bean> </list> </property> </bean>

而後再瀏覽器中訪問就能夠獲得json格式的數據了。

其實,通過測試發現,有的 spring版本不在springmvc.xml中進行josn轉換器配置也能夠轉換成json格式,springmvc有自動轉換功能,惋惜個人沒有。

controller代碼: 我用的是@ResponseBody註解實現的

//文件上傳控制器
@RequestMapping(value = "/uploadFile" , method = RequestMethod.POST) 
@ResponseBody
public JSONObject uploadPicture(@RequestParam("file")MultipartFile file,HttpServletRequest servletRequest) 
                throws IOException { 
        //若是文件內容不爲空,則寫入上傳路徑 
        //String str = "";
        JSONObject res = new JSONObject();
        JSONObject resUrl = new JSONObject();
        //上傳文件路徑 
        String path = servletRequest.getServletContext().getRealPath("/uploadFile");
        
        System.out.println("文件名稱"+file.getOriginalFilename()); 
        //上傳文件名         
        String name = file.getOriginalFilename();//上傳文件的真實名稱
        String suffixName = name.substring(name.lastIndexOf("."));//獲取後綴名
        String hash = Integer.toHexString(new Random().nextInt());//自定義隨機數(字母+數字)做爲文件名
        String fileName = hash + suffixName;        
        File filepath = new File(path, fileName); 
        System.out.println("隨機數文件名稱"+filepath.getName()); 
        //判斷路徑是否存在,沒有就建立一個 
        if (!filepath.getParentFile().exists()) { 
            filepath.getParentFile().mkdirs(); 
            } 
        //將上傳文件保存到一個目標文檔中 
        File tempFile = new File(path + File.separator + fileName);
        file.transferTo(tempFile);
        
        resUrl.put("src", tempFile.getPath());
        res.put("code", 0);
        res.put("msg", "");
        res.put("data", resUrl);
        //str = "{\"code\": 0,\"msg\": \"上傳成功\",\"data\": {\"src\":\""+path+fileName + "\"}}";
        System.out.println("res裏面的值:");
        System.out.println(res.toString());    
        return res;
    } 

 

效果圖:

 

注:未經許可,不得轉載。

相關文章
相關標籤/搜索