入门angular:文件的下载和上传

由于angular的火热

***服务器端:pom.xml*********************jar准备**************************************

1. 首先对文件spring和springMVC进行对文件的上传和下载首先需要下载jar包

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>

****服务器端:spring--MVC.xml********************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>

****服务器端:controller层**********************************************************************************

上传: 

  @RequestMapping(value = "/upload", produces = { "application/json" },
            method = RequestMethod.POST )
    public @ResponseBody  ResultData upload(
            @RequestParam(value = "logo", required = true)
                    MultipartFile excelfile){ 
        Boolean flag=reportService.readExcel(excelfile);
        return null;
    }

下载:

 @RequestMapping(value = "/download", method = RequestMethod.GET )
    public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{
  InputStream inputStream = null;
        XSSFWorkbook xWorkbook = null;
        try {
            ServletContext context = request.getSession().getServletContext();
            inputStream = context.getClassLoader().getResourceAsStream("/templates/商务计划书模板-目标.xlsx");
            xWorkbook = new XSSFWorkbook(inputStream);
            if (xWorkbook == null) {
                return;
            }
            String agent = request.getHeader("USER-AGENT").toLowerCase();
            response.setContentType("applicationnd.ms-excel");
            String fileName = "商务计划书模板-目标";
            String codedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            if (agent.contains("firefox")) {
                //火狐浏览器特殊处理
                response.setCharacterEncoding("utf-8");
                response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xlsx");
            } else {
                response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xlsx");
            }
            OutputStream os = response.getOutputStream();
            xWorkbook.write(response.getOutputStream());
            os.close();
            xWorkbook = null;
        } catch (Exception e) {
            logger.error("商务计划书模板导出失败", e);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

对应的前端页面

    <script src="framework/jquery-1.9.0.js"></script>
    <script src="framework/angular-1.3.0.14/angular.js"></script>
    <script src="framework/angular-1.3.0.14/angular-animate.min.js"></script>
    <script src="framework/angular-1.3.0.14/angular-file-upload.min.js"></script> 
    <script src="framework/angular-ui-router.js"></script>
    <script src="framework/ui-bootstrap-tpls-0.11.0.js"></script>
    <script src="js/app.js"></script>

<body ng-app="app">
<div  ng-controller="UploaderController" >
<input type="file" file-model="myFile" >
<button ng-click="save()" >上传</button>
<button ng-click="download()" >下载</button>
</div>
</body>以下就是js代码:

 var app=angular.module('app',[]);
app.controller('UploaderController',function($scope,$http){

    $scope.save = function() {
        var fd = new FormData();
        var file = document.querySelector('input[type=file]').files[0];
        fd.append('logo', file);//angular 上传的文件必须使用特殊的格式处理,不是json格式
        $http({
            method:'POST',
            url:"http://localhost:8080/report/upload",
            data: fd,
            headers: {'Content-Type':undefined},// 写成是undifined,浏览器才自动转化为 文件上传的类型
            transformRequest: angular.identity
        }).success( function ( response )
            {
                //上传成功的操作
                alert("uplaod success");
            });

    }

 /*   经验总结:
1.post的方法里要加responseType: 'arraybuffer'参数,不然下载的excel会乱码
2.使用{type: "application/vnd.ms-excel"}的写法,可以保存为xls格式的excel文件
而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”则会保存为xlsx
 3.使用增加节点调用click方法
    */
    $scope.download = function() {
        $http({
            method:'GET',
            url:"http://localhost:8080/report/download",
            responseType: "arraybuffer"
        }).success( function ( data )
        {     // 这里会弹出一个下载框,增强用户体验
            var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
            var objectUrl = URL.createObjectURL(blob);
            //  创建a标签模拟下载
            var aForExcel = $("<a><span class='forExcel'>下载excel</span></a>").attr("href",objectUrl);
            $("body").append(aForExcel);
            $(".forExcel").click();
            aForExcel.remove();
        });

    }

});


Angular中请求文件流通常是处理从服务器下载文件(如图片、PDF、视频等)或者上传文件到服务器。这里主要介绍如何在Angular中使用HttpClient模块下载文件流。 首先,确保你的Angular项目中已经导入了HttpClientModule,在你的app.module.ts文件中添加HttpClientModule: ```typescript import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule, // 其他模块... ], }) export class AppModule { } ``` 接下来,创建一个服务或组件来处理HTTP请求: 1. 下载文件流(下载到本地) ```typescript import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class FileService { private baseUrl = 'http://example.com/api'; // 服务器API基础URL constructor(private http: HttpClient) {} downloadFile(fileId: string): Observable<Blob> { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), responseType: 'blob' as 'json' }; return this.http.get(this.baseUrl + '/download/' + fileId, httpOptions).pipe( map(response => { const contentType = response.headers.get('content-type'); const contentDisposition = response.headers.get('content-disposition'); const blob = new Blob([response], { type: contentType }); return blob; }) ); } } ``` 在组件中调用服务方法: ```typescript import { Component, OnInit } from '@angular/core'; import { FileService } from './file.service'; import { saveAs } from 'file-saver'; @Component({ selector: 'app-download-file', templateUrl: './download-file.component.html', styleUrls: ['./download-file.component.css'] }) export class DownloadFileComponent implements OnInit { constructor(private fileService: FileService) { } ngOnInit() { this.downloadAndSaveFile('12345'); } downloadAndSaveFile(fileId: string): void { this.fileService.downloadFile(fileId).subscribe(blob => { saveAs(blob, 'downloaded-file.pdf'); // 使用file-saver库保存文件 }); } } ``` 2. 上传文件流(发送到服务器) ```typescript import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class FileService { private baseUrl = 'http://example.com/api'; // 服务器API基础URL constructor(private http: HttpClient) {} uploadFile(file: File): Observable<any> { const formData: FormData = new FormData(); formData.append('file', file); const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'multipart/form-data' }) }; return this.http.post(this.baseUrl + '/upload', formData, httpOptions); } } ``` 在组件中调用服务方法: ```typescript import { Component } from '@angular/core'; import { FileService } from './file.service'; @Component({ selector: 'app-upload-file', templateUrl: './upload-file.component.html', styleUrls: ['./upload-file.component.css'] }) export class UploadFileComponent { constructor(private fileService: FileService) { } upload() { const fileInput = document.getElementById('file-input') as HTMLInputElement; const file = fileInput.files[0]; if (file) { this.fileService.uploadFile(file).subscribe(response => { console.log('File uploaded successfully', response); }, error => { console.error('File upload failed', error); }); } else { console.log('Please select a file to upload.'); } } } ``` 确保在你的HTML文件中提供一个文件输入控件: ```html <input type="file" id="file-input"> <button (click)="upload()">Upload File</button> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值