工作中遇到的小问题,做个笔记
实现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); } }
时间: 2024-10-23 09:45:00