layUI框架中文件上传前后端交互及遇到的相关问题
下面我將講述一下我在使用layUI框架中文件上傳所遇到的問題:
前端jsp頁面:
<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"></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) @ResponseBodypublic 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;} }報“請求上傳接口異常”問題,一般的解決方法:
?1、后臺返回到前臺的json數據一直報數據接口異常
第一,檢查自己返回的json數據格式是否正常,該接口返回的相應信息(response)必須是一個標準的 JSON 格式,如:返回的數據格式是否是
{"code": 0,"msg": "","data": {"src": "http://cdn.layui.com/123.jpg"} }返回的數據格式是這樣的,但是還是報數據接口異常的話
第二,msg的值一定要寫"",不然會一直報錯,自己設定的code值一定要寫0,其他的值都是錯誤的。
2、json數據包是否配置好,我就是這樣才導致一直報錯
在?SpringController.java中需要如下代碼:并在構建路徑中引入 這兩個jar包,才能支持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轉換器配置 --><beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><!-- json轉換器 --><property name="messageConverters"><list><beanclass="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;}?
效果圖:
?
注:未經許可,不得轉載。
轉載于:https://www.cnblogs.com/qiantao/p/10056459.html
總結
以上是生活随笔為你收集整理的layUI框架中文件上传前后端交互及遇到的相关问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 常见异常集合
- 下一篇: 基本类型和引用类型的值 函数的传递参数