1.需要ajaxfileupload.js 和 jQery.js 、GSON包
2.spring.xml 配置
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<!-- set the max upload size1MB 1048576 -->
<property name="maxUploadSize">
<value>52428800</value>
</property>
<property name="maxInMemorySize">
<value>2048</value>
</property>
</bean>
3. JSP页面
<input type="button" id="import" class="btn btn-primary" style="width: 110px" value="Excel导入"> <input style="display: none" type="file" id="file" name="file" onchange="excelUpload();"/> <script type="text/javascript"> //Excel导入ajax $("#import").click(function() { $("#file").click(); }); function excelUpload() { $.ajaxFileUpload({ url : ‘${pageContext.request.contextPath}/rest/priceShipownerService/excelUpload.json‘, secureuri : false, fileElementId : ‘file‘, dataType : ‘json‘, success : function(data) { alert(data.msg); location.reload(); } });} </script>
4.后台java接收
1 public void excelUpload(MultipartHttpServletRequest multipartRequest, 2 HttpServletResponse response) throws Exception { 3 response.setContentType("text/html;charset=UTF-8"); 4 Map<String, Object> result = new HashMap<String, Object>(); 5 6 String key = multipartRequest.getFileNames().next(); 7 MultipartFile file = multipartRequest.getFile(key); 8 String fileName = file.getOriginalFilename(); 9 InputStream is = file.getInputStream(); 10 String msg = this.priceShipownerImportExcel(fileName, is); 11 result.put("msg", msg); 12 String json = new Gson().toJson(result, 13 new TypeToken<Map<String, Object>>() { 14 }.getType()); 15 response.getWriter().print(json); 16 17 }
时间: 2024-10-06 00:07:08