html篇
<!-- 下载文件 --> <div> <a (click)="getFile()">点我测试post方式下载文件</a> </div> <!-- 上传单个文件 --> <div> <input type="file" (change)="uploadFile($event)" name="value" value="测试上传单个文件"/> </div> <!-- 上传多个文件 --> <div > <input type="file" multiple (change)="uploadFiles($event)" name="files" value="测试上传单个文件"/> </div>
组件方法篇
export class PostDownloadComponent implements OnInit { baseUrl = "http://localhost:8098/"; constructor(private http: Http ) { } ngOnInit() { } // post方式下载文件 getFile() { let head = new Headers({ 'Content-Type': 'application/json' }); let url = this.baseUrl + "user/exportExcel"; let body = ["343434", "343434", "34342323", "34rty6y654"]; let b = JSON.stringify(body); let options = new RequestOptions({ headers: head, responseType: 3 }); return this.http.post(url, b, options).toPromise().then( res => { let file = new File([res.json()], "mm.xls", { type: "application/vnd.ms-excel" }); var objUrl = URL.createObjectURL(file); window.open(objUrl); URL.revokeObjectURL(objUrl) }); } // post方式上传单个文件 uploadFile(event) { let file: FormData = new FormData(); let fileList: FileList = event.target.files; if (fileList.length > 0) { let file: File = fileList[0]; let formData: FormData = new FormData(); formData.append('value', file, file.name); let headers = new Headers(); headers.append('Accept', 'application/json'); let options = new RequestOptions({ headers: headers }); let url = this.baseUrl + "user/importExcel"; this.http.post(url, formData, options).toPromise().then(res => { console.log(res.json()) }) } } // post方式上传多个文件 uploadFiles(event) { let fileList: FileList = event.target.files; const fileLength = fileList.length; const formData: FormData = new FormData(); for (let index = 0; index < fileLength; index++) { let singleFile = fileList.item(index); // files 这个名字和spring mvc controller参数的名字要对应 formData.append('files', singleFile); } let headers = new Headers(); headers.append('Accept', 'application/json'); let options = new RequestOptions({ headers: headers }); let url = this.baseUrl + "user/importExcelList"; this.http.post(url, formData, options).toPromise().then(res => { console.log(res.json()) }) } }
Java后台篇
@Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService; @RequestMapping("/selectUser") public UserVO selectUserById(Long userId) { return userService.selectUserById(userId); } @RequestMapping(value = "/exportExcel", method = RequestMethod.POST) public void exportExcel(HttpServletRequest request, HttpServletResponse response, @RequestBody String[] str) { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(); HSSFRow row1 = sheet.createRow(0); HSSFCell cell = row1.createCell(0); cell.setCellValue("学院考试成绩一览表"); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); List<UserVO> list = new ArrayList<>(10); for (int i = 0; i < 4; i++) { UserVO vo = new UserVO(); vo.setEmail("[email protected]"); vo.setPassWord(String.valueOf(i)); vo.setUserName("wgp" + i); vo.setPhone("110" + i); list.add(vo); } int len = list.size(); HSSFRow ro = sheet.createRow(1); ro.createCell(0).setCellValue("姓名"); ro.createCell(1).setCellValue("密码"); ro.createCell(2).setCellValue("邮箱"); ro.createCell(3).setCellValue("手机号"); for (int i = 0; i < len; i++) { HSSFRow ro1 = sheet.createRow(i + 2); ro1.createCell(0).setCellValue(list.get(i).getUserName()); ro1.createCell(1).setCellValue(list.get(i).getPassWord()); ro1.createCell(2).setCellValue(list.get(i).getEmail()); ro1.createCell(3).setCellValue(list.get(i).getPhone()); } try { OutputStream out = response.getOutputStream(); wb.write(out); response.setHeader("Content-disposition", "attachment; filename=details.xls"); // response.setContentType("application/msexcel"); response.setContentType("application/vnd.ms-excel"); out.close(); } catch (IOException e) { e.printStackTrace(); } } @RequestMapping(value = "/importExcel", method = RequestMethod.POST) @ResponseBody public ResultData importExcel(@RequestParam("value") MultipartFile file) { System.out.println(file.getOriginalFilename()); System.out.println(file.getName()); String fileName = file.getOriginalFilename(); int len = fileName.lastIndexOf("."); String prefix = fileName.substring(0, fileName.lastIndexOf(".")); String stufix = fileName.substring(len, fileName.length()); OutputStream out = null; try { out = new FileOutputStream("D:////" + prefix + System.currentTimeMillis() + ".xls"); out.write(file.getBytes()); out.close(); } catch (Exception e) { e.printStackTrace(); return new ResultData("1", "fail", false); } return new ResultData("0", "successfully", true); } @RequestMapping(value="/importExcelList",method = RequestMethod.POST) @ResponseBody public ResultData importExcelList(@RequestParam("files") List<MultipartFile> files) { int length = files.size(); try { for (int i = 0; i < length; i++) { String fileName = files.get(i).getOriginalFilename(); int len = fileName.lastIndexOf("."); String prefix = fileName.substring(0, fileName.lastIndexOf(".")); String stufix = fileName.substring(len, fileName.length()); OutputStream out = null; out = new FileOutputStream("D://test//" + prefix + System.currentTimeMillis() + stufix); out.write(files.get(i).getBytes()); out.close(); } } catch (Exception e) { e.printStackTrace(); return new ResultData("1", "fail", false); } return new ResultData("0", "successfully", true); } }
问题篇
前天不要加上 multipart/form-data的header,加上这个纯属画蛇添足。
后台要加上 common-fileuploadjar包。
纯属demo篇
加入项目还需做美化,验证,规范代码等处理。