工作中遇到的小問題,做個筆記 實現springMVC + jsp + ajax 上傳文件 HTML javascript springMVC.xml java ...
工作中遇到的小問題,做個筆記
實現springMVC + jsp + ajax 上傳文件
HTML
<body> <form id="myform" method="post" > 登錄名<input type="text" name="loginName" /> <br> 上傳錄音<input type="file" name="record" /> <input type="button" onclick="doUpload()" value="提交" /> </form> </body>
javascript
function doUpload() { var formData = new FormData($( "#myform" )[0]); $.ajax({ url: 'insert/fileupload.action' , type: 'POST', data: formData, async: false, cache: false, contentType: false, processData: false, success: function (returndata) { alert(returndata); }, error: function (returndata) { alert(returndata); } }); }
springMVC.xml
<!-- 配置文件上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxUploadSize" value="10485760000"/> <property name="maxInMemorySize" value="40960"/> </bean>
java
RequestMapping("fileupload") public void fileupload(HttpServletRequest request,HttpServletResponse response,String loginName) throws Exception { //獲取伺服器中保存文件的路徑 String path = request.getSession().getServletContext().getRealPath("")+"\\upload\\record\\"; System.out.println(path); //獲取解析器 CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判斷是否是文件 if(resolver.isMultipart(request)){ //進行轉換 MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)(request); //獲取所有文件名稱 Iterator<String> it = multiRequest.getFileNames(); while(it.hasNext()){ //根據文件名稱取文件 MultipartFile file = multiRequest.getFile(it.next()); String fileName = file.getOriginalFilename(); String localPath = path + fileName; //創建一個新的文件對象,創建時需要一個參數,參數是文件所需要保存的位置 File newFile = new File(localPath); //上傳的文件寫入到指定的文件中 file.transferTo(newFile); } }