Java前后端的上传和下载
上传
前端代码
1 2 3 4 5 6 7
| "使用了bootstrap样式" <label class="input-group-btn"> <span class="btn btn-success"> <i class="fas fa-file-upload"></i> 导入数据<input id="myFile" type="file" name="file" style="display: none;"> </span> </label>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| "Jquery代码上传"
$("#myFile").on('change',function () { "创建formData" var formData = new FormData(); "获取文件数据" var file = $("#myFile")[0].files[0]; formData.append("files",file); $.ajax({ type: "POST", url: "<%=request.getContextPath()%>/jtxyh/uploadFile", dataType : "json", mimeType:"multipart/form-data", processData: false, "注意:让jQuery不要处理数据" contentType: false, "注意:让jQuery不要设置contentType" data: formData, success:function (data) { "这里写上传后操作" } }) });
|
后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| @PostMapping("/uploadFile") @ResponseBody "这里这个必须这样写" public List<String> uploadFile(@RequestParam(value = "files", required = false) MultipartFile multipartFile) { "存储已经存在的数据" List<String> alreadyData = new ArrayList<>(); "存入数据库的数据" List<CommBrand> newData = new ArrayList<>(); if (multipartFile != null) { InputStream inputStream = null; try { inputStream = multipartFile.getInputStream(); } catch (Exception e) { e.printStackTrace(); } "调用读取Excel的工具类" List<CommBrand> commBrands = ReadCommBrandExcelUtil.readExcel(inputStream); "判断数据是否重复" for (int i = 0; i < commBrands.size(); i++) { "查询这条数据是否存在数据库中" int count = commBrandService.selectByBrandNameReInt(commBrands.get(i).getBrandName()); "如果大于0代表数据库中已经有这个数据了" if (count > 0) { alreadyData.add(commBrands.get(i).getBrandName()); } else { newData.add(commBrands.get(i)); } } if (newData.size() != 0) { "批量添加数据" insertBulkCommBrand(newData); } } return alreadyData; }
|
下载
前端代码
1 2 3
| <button id="downloadBtn" type="button" class="btn btn-success btn-block"> <i class="fas fa-download"></i> <span>下载</span> </button>
|
1
| window.location.href = '<%=request.getContextPath()%>/deliverInfo/download?拼上需要上传的数据;'
|
后端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @GetMapping("/download") public void downloadDeliverInfo(String deliverIdArray, HttpServletResponse response){ "调用工具类下载" try { "设置响应流" response.setHeader("content-disposition", "attoachment;fileName="+URLEncoder.encode(new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date()),"UTF-8") +".docx"); OutputStream outputStream = response.getOutputStream(); word.write(deliverIdArray,outputStream); byte buffer[] = new byte[1024]; outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
|
相关文章
数据库连接池
SpringIOC
Junit和Spring
Tomcat
Servlet
Request,Response和ServletContext
Cookie和Session
JSP和EL和Jstl
Filter和Listener
Mybatis