我是Angular的初学者,我想知道如何创建Angular 5文件上传部分,我试图找到任何教程或文档,但我在任何地方都看不到任何东西。对此有什么想法吗?我尝试了ng4-files,但它不适用于Angular 5
当前回答
超文本标记语言
<div class="form-group">
<label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
</div>
<button type="button" (click)="RequestUpload()">Ok</button>
ts文件
public formData = new FormData();
ReqJson: any = {};
uploadFiles( file ) {
console.log( 'file', file )
for ( let i = 0; i < file.length; i++ ) {
this.formData.append( "file", file[i], file[i]['name'] );
}
}
RequestUpload() {
this.ReqJson["patientId"] = "12"
this.ReqJson["requesterName"] = "test1"
this.ReqJson["requestDate"] = "1/1/2019"
this.ReqJson["location"] = "INDIA"
this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
this.http.post( '/Request', this.formData )
.subscribe(( ) => {
});
}
后端Spring(java文件)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Request {
private static String UPLOADED_FOLDER = "c://temp//";
@PostMapping("/Request")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
System.out.println("Json is" + Info);
if (file.isEmpty()) {
return "No file attached";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "Succuss";
}
}
我们必须在C驱动器中创建一个文件夹“temp”,然后这段代码将在控制台中打印Json并将上传的文件保存在创建的文件夹中
其他回答
试试这个
安装
npm install primeng --save
进口
import {FileUploadModule} from 'primeng/primeng';
Html
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
使用Angular和nodejs上传文件的完整示例(express)
HTML代码
<div class="form-group">
<label for="file">Choose File</label><br/>
<input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
</div>
TS组件代码
uploadFile(files) {
console.log('files', files)
var formData = new FormData();
for(let i =0; i < files.length; i++){
formData.append("files", files[i], files[i]['name']);
}
this.httpService.httpPost('/fileUpload', formData)
.subscribe((response) => {
console.log('response', response)
},
(error) => {
console.log('error in fileupload', error)
})
}
Node Js代码
上传火灾控制器
function start(req, res) {
fileUploadService.fileUpload(req, res)
.then(fileUploadServiceResponse => {
res.status(200).send(fileUploadServiceResponse)
})
.catch(error => {
res.status(400).send(error)
})
}
module.exports.start = start
使用multer上传服务
const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'
/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g, '_'))
}
})
/** Upload files */
let upload = multer({ storage: storage }).array('files')
/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
let deferred = q.defer()
/** Create dir if not exist */
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir)
console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
}
upload(req, res, function (err) {
if (req && (_.isEmpty(req.files))) {
deferred.resolve({ status: 200, message: 'File not attached', data: [] })
} else {
if (err) {
deferred.reject({ status: 400, message: 'error', data: err })
} else {
deferred.resolve({
status: 200,
message: 'File attached',
filename: _.pluck(req.files,
'filename'),
data: req.files
})
}
}
})
return deferred.promise
}
}
下面是我上传excel文件的方法: 目录结构:
app
|-----uploadcomponent
|-----uploadcomponent.module.ts
|-----uploadcomponent.html
|-----app.module.ts
|-----app.component.ts
|-----app.service.ts
uploadcomponent.html
<div>
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input type="file" name="profile" enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" />
<button type="submit">Upload Template</button>
<button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button>
</form>
</div>
uploadcomponent.ts
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
....
export class UploadComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
ngOnInit() {
this.form = this.formBuilder.group({
profile: ['']
});
}
onChange(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.form.get('profile').setValue(file);
console.log(this.form.get('profile').value)
}
}
onSubmit() {
const formData = new FormData();
formData.append('file', this.form.get('profile').value);
this.uploadService.upload(formData).subscribe(
(res) => {
this.response = res;
console.log(res);
},
(err) => {
console.log(err);
});
}
}
app.service.ts
upload(formData) {
const endpoint = this.service_url+'upload/';
const httpOptions = headers: new HttpHeaders({ <<<< Changes are here
'Authorization': 'token xxxxxxx'})
};
return this.http.post(endpoint, formData, httpOptions);
}
在后台,我使用DJango REST框架。 models.py
from __future__ import unicode_literals
from django.db import models
from django.db import connection
from django_mysql.models import JSONField, Model
import uuid
import os
def change_filename(instance, filename):
extension = filename.split('.')[-1]
file_name = os.path.splitext(filename)[0]
uuid_name = uuid.uuid4()
return file_name+"_"+str(uuid_name)+"."+extension
class UploadTemplate (Model):
id = models.AutoField(primary_key=True)
file = models.FileField(blank=False, null=False, upload_to=change_filename)
def __str__(self):
return str(self.file.name)
views.py。
class UploadView(APIView):
serializer_class = UploadSerializer
parser_classes = [MultiPartParser]
def get_queryset(self):
queryset = UploadTemplate.objects.all()
return queryset
def post(self, request, *args, **kwargs):
file_serializer = UploadSerializer(data=request.data)
status = None
message = None
if file_serializer.is_valid():
file_serializer.save()
status = "Success"
message = "Success"
else:
status = "Failure"
message = "Failure!"
content = {'status': status, 'message': message}
return Response(content)
serializers.py。
from uploadtemplate.models import UploadTemplate
from rest_framework import serializers
class UploadSerializer(serializers.ModelSerializer):
class Meta:
model = UploadTemplate
fields = '__all__'
urls . py。
router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView,
base_name='UploadTemplate')
urlpatterns = [
....
url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
MEDIA_URL和MEDIA_ROOT在项目的settings.py中定义。
谢谢!
通过这种方式,我实现了在项目中上传文件到web API。
我为谁分担关心。
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
一步一步
ASP。网上广告
[HttpPost]
[Route("api/dashboard/UploadImage")]
public HttpResponseMessage UploadImage()
{
string imageName = null;
var httpRequest = HttpContext.Current.Request;
//Upload Image
var postedFile = httpRequest.Files["Image"];
//Create custom filename
if (postedFile != null)
{
imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(10).ToArray()).Replace(" ", "-");
imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
var filePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
postedFile.SaveAs(filePath);
}
}
HTML表单
<form #imageForm=ngForm (ngSubmit)="OnSubmit(Image)">
<img [src]="imageUrl" class="imgArea">
<div class="image-upload">
<label for="file-input">
<img src="upload.jpg" />
</label>
<input id="file-input" #Image type="file" (change)="handleFileInput($event.target.files)" />
<button type="submit" class="btn-large btn-submit" [disabled]="Image.value=='' || !imageForm.valid"><i
class="material-icons">save</i></button>
</div>
</form>
TS文件使用API
OnSubmit(Image) {
this.dashboardService.uploadImage(this.componentId, this.fileToUpload).subscribe(
data => {
console.log('done');
Image.value = null;
this.imageUrl = "/assets/img/logo.png";
}
);
}
服务TS
uploadImage(componentId, image) {
const formData: FormData = new FormData();
formData.append('Image', image, image.name);
formData.append('ComponentId', componentId);
return this.http.post('/api/dashboard/UploadImage', formData);
}
超文本标记语言
<div class="form-group">
<label for="file">Choose File</label><br /> <input type="file" id="file" (change)="uploadFiles($event.target.files)">
</div>
<button type="button" (click)="RequestUpload()">Ok</button>
ts文件
public formData = new FormData();
ReqJson: any = {};
uploadFiles( file ) {
console.log( 'file', file )
for ( let i = 0; i < file.length; i++ ) {
this.formData.append( "file", file[i], file[i]['name'] );
}
}
RequestUpload() {
this.ReqJson["patientId"] = "12"
this.ReqJson["requesterName"] = "test1"
this.ReqJson["requestDate"] = "1/1/2019"
this.ReqJson["location"] = "INDIA"
this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
this.http.post( '/Request', this.formData )
.subscribe(( ) => {
});
}
后端Spring(java文件)
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class Request {
private static String UPLOADED_FOLDER = "c://temp//";
@PostMapping("/Request")
@ResponseBody
public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
System.out.println("Json is" + Info);
if (file.isEmpty()) {
return "No file attached";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return "Succuss";
}
}
我们必须在C驱动器中创建一个文件夹“temp”,然后这段代码将在控制台中打印Json并将上传的文件保存在创建的文件夹中
推荐文章
- 如何在Typescript中解析JSON字符串
- TypeScript中的extends和implements有什么区别
- 如何用angular 2路由器重新加载当前路由
- 创建组件与Angular-CLI &将它添加到一个特定的模块
- 迭代Typescript Map
- 定义TypeScript回调类型
- @HostBinding和@HostListener:它们是做什么用的?
- 如何在TypeScript中实现睡眠函数?
- 在Angular 6中生成服务时,为din提供可注入装饰器的目的是什么?
- 返回一个空的Observable
- 为什么——isolatedModules错误被任何导入修复?
- 如何用npm更新TypeScript到最新版本?
- 如何在angular2中调用另一个组件函数
- Angular 2可选的路由参数
- Typescript:在类型“{" a ":字符串上找不到参数类型为'string'的索引签名;}