You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Angular本地项目实现PDF文件上传至assets文件夹需求咨询

实现Angular本地项目PDF上传至Assets文件夹

对于本地运行的Angular项目,要实现PDF上传到assets文件夹的功能,首先得明确一个关键限制:浏览器端代码无法直接写入本地项目的文件系统——这是浏览器的安全沙箱机制导致的。所以我们需要结合一个本地Node.js服务来处理文件写入操作,以下是针对你的Angular 11版本的完整实现步骤:

1. 安装必要依赖

首先在项目根目录安装用于文件上传的Node.js工具包:

npm install express multer cors --save-dev
  • express:搭建本地API服务
  • multer:处理文件上传的中间件
  • cors:解决Angular和Node服务之间的跨域问题

2. 编写本地文件上传服务

在项目根目录创建一个名为file-upload-server.js的文件,写入以下代码:

const express = require('express');
const multer = require('multer');
const cors = require('cors');
const path = require('path');
const fs = require('fs');

const app = express();
app.use(cors());

// 配置文件存储路径:指向项目的src/assets/pdf目录(自动创建不存在的目录)
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, 'src/assets/pdf');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 可选:添加时间戳避免文件名重复覆盖
    // const timestamp = Date.now();
    // cb(null, `${timestamp}-${file.originalname}`);
    cb(null, file.originalname); // 保留原文件名
  }
});

const upload = multer({ storage: storage });

// 定义PDF上传接口
app.post('/upload-pdf', upload.single('pdfFile'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('未选择上传文件');
  }
  res.status(200).send({
    message: '文件上传成功',
    filePath: `assets/pdf/${req.file.originalname}`
  });
});

// 启动服务,监听3000端口
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`文件上传服务已启动:http://localhost:${PORT}`);
});

3. 创建Angular上传组件

生成一个专门处理PDF上传的组件:

ng generate component upload-pdf

组件模板(upload-pdf.component.html)

<div class="upload-wrapper">
  <h3>上传PDF到Assets目录</h3>
  <input type="file" accept=".pdf" (change)="onFileSelected($event)" class="file-input">
  <button (click)="uploadFile()" [disabled]="!selectedFile" class="upload-btn">
    上传文件
  </button>
  <p *ngIf="uploadStatus" class="status-text">{{uploadStatus}}</p>
</div>

组件逻辑(upload-pdf.component.ts)

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-upload-pdf',
  templateUrl: './upload-pdf.component.html',
  styleUrls: ['./upload-pdf.component.css']
})
export class UploadPdfComponent {
  selectedFile: File | null = null;
  uploadStatus: string | null = null;
  private uploadApiUrl = 'http://localhost:3000/upload-pdf';

  constructor(private http: HttpClient) { }

  // 选择文件时的处理逻辑
  onFileSelected(event: Event): void {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
      if (file.type === 'application/pdf') {
        this.selectedFile = file;
        this.uploadStatus = null;
      } else {
        this.uploadStatus = '请选择PDF格式的文件';
        this.selectedFile = null;
      }
    }
  }

  // 执行文件上传
  uploadFile(): void {
    if (!this.selectedFile) return;

    const formData = new FormData();
    formData.append('pdfFile', this.selectedFile);

    this.http.post<any>(this.uploadApiUrl, formData).subscribe({
      next: (response) => {
        this.uploadStatus = `上传成功!文件路径:${response.filePath}`;
        // 这里可以添加逻辑通知PDF查看组件刷新文件列表
      },
      error: (err) => {
        this.uploadStatus = `上传失败:${err.message}`;
      }
    });
  }
}

组件样式(可选,upload-pdf.component.css)

.upload-wrapper {
  max-width: 400px;
  margin: 2rem auto;
  padding: 1.5rem;
  border: 1px solid #eee;
  border-radius: 8px;
}

.file-input {
  display: block;
  margin: 1rem 0;
}

.upload-btn {
  padding: 0.5rem 1rem;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.status-text {
  margin-top: 1rem;
  color: #333;
}

4. 配置Angular的HttpClientModule

app.module.ts中导入HttpClientModule,确保组件能发起HTTP请求:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    // ...你的组件声明
    UploadPdfComponent
  ],
  imports: [
    // ...其他导入
    HttpClientModule
  ],
  // ...
})
export class AppModule { }

5. 启动服务并测试

  1. 先启动本地文件上传服务:
node file-upload-server.js
  1. 再启动Angular项目:
ng serve

现在你可以在页面中使用<app-upload-pdf></app-upload-pdf>组件上传PDF文件,文件会被写入到src/assets/pdf目录,你的PDF查看组件可以直接通过assets/pdf/[文件名]的路径访问这些文件。

注意事项

  • 文件名重复:如果需要避免同名文件覆盖,可以修改file-upload-server.js中的filename配置,添加时间戳前缀。
  • assets同步:Angular的ng serve会自动监测src/assets目录的文件变化,上传后无需重启Angular服务即可访问新文件。
  • 本地运行限制:这个方案仅适用于本地开发环境,生产环境需要后端服务配合存储文件(而非直接写入项目目录)。

内容的提问来源于stack exchange,提问作者l3onh4rd

火山引擎 最新活动