您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)在SpringMvc項(xiàng)目中使用Angularjs 如何實(shí)現(xiàn)一個(gè)文件上傳功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
SpringMvc代碼
jar包
commons-fileupload
commons-io
spring-mvc.xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8" /> </bean>
Controller
@RequestMapping(value = "api/v1/upload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Map upload (@RequestParam(value = "files") MultipartFile [] files, @RequestParam(value = "id") String id, HttpServletRequest request, HttpServletResponse response) { Map res = new HashMap(); try { log.info("upload>>>>>id:{}", id); if (files!=null) { for (MultipartFile file:files) { log.info("filename:{}", file.getOriginalFilename()); } } } catch (Exception e) { log.error("upload>>>>異常:{}", e.toString()); } log.info("upload>>>>返回結(jié)果:{}", res); return res; }
保存到本地
// copy File public boolean copyFile (MultipartFile tempFile, String filePath) { Boolean res = false; try { File file = new File(filePath); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } // 將文件拷貝到當(dāng)前目錄下 tempFile.transferTo(file); res = true; } catch (Exception e) { log.info("copyFile>>>>異常:{}", e.toString()); } return res; }
AngularJs代碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="uploadCtrl"> <p><input type="file" multiple="multiple" name="files"></p> <p><input type="text" name="id" ng-model="id"></p> <p><input type="button" value="提交" ng-click="submit()"></p> </div> <script> var app = angular.module('myApp', []); app.controller('uploadCtrl', ["$scope", "$http", function($scope, $http) { $scope.submit = function () { var fd = new FormData(); var files = document.querySelector('input[name="files"]').files; for (var i=0; i<files.length; i++) { fd.append("files", files[i]); } fd.append("id", $scope.id); $http({ method:'POST', url : '/Project/api/v1/upload', data: fd, headers: {'Content-Type':undefined}, transformRequest: angular.identity }).success(function (response) { console.log(response.data); }).error(function () { }); } }]); </script> </body> </html>
Form表單提交
<form action="/Project/api/v1/upload" method="POST" enctype="multipart/form-data"> <p><input type="text" name="id" /></p> <p><input type="file" multiple="multiple" id="files" name="files" /></p> <p><input type="submit" value="Submit" /></p> </form>
關(guān)于在SpringMvc項(xiàng)目中使用Angularjs 如何實(shí)現(xiàn)一個(gè)文件上傳功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。