我尝试将Angular应用中的图片上传到Laravel。我的问题是无法完成。我的代码有问题吗?我也必须使用其他输入字段来提交它。请在下面检查我的代码。
HTML
<form [formGroup]="servicesForm" (ngSubmit)="onCreateService(servicesForm)">
<div class="col-sm-8">
<input type="file" accept=".png, .jpg, .jpeg" (change)="onSelectImage($event)" class="form-control" formControlName="icon">
</div>
<button type="submit" >Save</button>
</form>
TS
onSelectImage(event) {
this.selectedImage = new FormData();
this.selectedImage.append('avatar', event.srcElement.files[0], event.srcElement.files[0].name);
console.log(this.selectedImage);
}
onCreateService(form: FormGroup) {
const formData = {
image: this.selectedImage,
name: this.servicesForm.get('name').value,
amount: this.servicesForm.get('price').value,
description: this.servicesForm.get('content').value
};
console.log(formData);
}
答案 0 :(得分:1)
您需要像下面那样更改ts
代码,不仅需要将图像作为formdata
发送整个数据
onSelectImage(event) {
this.selectedImage = event.srcElement.files[0];
}
onCreateService(form: FormGroup) {
const formData = new FormData();
formData.append('image', this.selectedImage, this.selectedImage.name);
formData.append('name', this.servicesForm.get('name').value);
formData.append('amount', this.servicesForm.get('price').value);
formData.append('description', this.servicesForm.get('content').value);
console.log(formData);
}
答案 1 :(得分:0)
index.html
<body ng-controller="myCtrl">
<div class="file-upload">
<input type="text" ng-model="name">
<input type="file" file-model="myFile"/>
<button ng-click="uploadFile()">upload me</button>
</div>
app.js
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
// We can write our own fileUpload service to reuse it in the controller
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl, name){
var fd = new FormData();
fd.append('file', file);
fd.append('name', name);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined,'Process-Data': false}
})
.success(function(){
console.log("Success");
})
.error(function(){
console.log("Success");
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "save_form.php";
var text = $scope.name;
fileUpload.uploadFileToUrl(file, uploadUrl, text);
};
}]);
save_form.php
<?php
$target_dir = "./upload/";
$name = $_POST['name'];
print_r($_FILES);
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
//write code for saving to database
include_once "config.php";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyData (name,filename) VALUES ('".$name."','".basename($_FILES["file"]["name"])."')";
if ($conn->query($sql) === TRUE) {
echo json_encode($_FILES["file"]); // new file uploaded
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
答案 2 :(得分:0)
您尝试使用此编码。此图片 Uploding 代码使用前端 Angular 到后端 Laravel-8。
以下是 Angular ts 文件编码。 saveOrUpdate 包含文件保存编码和更新编码
import { Component, OnInit } from '@angular/core';
import { FormBuilder} from '@angular/forms';
import { Product } from '../../models/product.model';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../../environments/environment';
@Component({
selector: 'app-add-product',
templateUrl: './add-product.component.html',
styleUrls: ['./add-product.component.css']
})
export class AddProductComponent implements OnInit {
file: any;
imagePath: any;
currentSupplierId: number;
constructor(
private formBuilder: FormBuilder,
private http: HttpClient,
) { }
ngOnInit() {
this.imagePath = environment.baseUrl + "/public/img/products/";
}
onFileChanged(event) {
console.log(event);
this.file = event.target.files[0];
const reader = new FileReader();
reader.onload = e => {
return this.imageSrc = reader.result;
};
reader.readAsDataURL(this.file);
}
saveOrUpdate(product: Product) {
debugger;
const myFormData = new FormData();
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
myFormData.append('image', this.file);
myFormData.append('code', product.code);
this.http.post(environment.utilityApiBasePath + 'upload', myFormData, {
headers: headers
}).subscribe(data => {
console.log(data);
});
} else {
const myFormData = new FormData();
const headers = new HttpHeaders();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
myFormData.append('image', this.file);
myFormData.append('code', product.code);
this.http.delete(environment.utilityApiBasePath + 'deleteImage/' + product.code + '.jpg').subscribe(
data1 => {
console.log(data1);
this.http.post(environment.utilityApiBasePath + 'upload', myFormData, {
headers: headers
}).subscribe(data => {
console.log(data);
});
});
}
这是 Larwell 控制器文件编码。
$file->move(public_path('supplier'), $picture);
我们需要在 supplier 上面的编码中创建平行的路径。在这个路径中应该是我们在Larwell文件的public文件夹中创建的。
public function uploadProfilePhoto(Request $request) {
if ($request->hasFile('image'))
{
$file = $request->file('image');
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
// $picture = date('His').'-'.$filename;
$picture = $request['code'].'.jpg';
$file->move(public_path('/supplier'), $picture);
return response()->json(["message" => "Image Uploaded Succesfully"]);
}
else
{
return response()->json(["message" => "Select image first."]);
}
}
这将在我更新时删除文件夹中的旧图像,然后重新兑现新图像。所以下面是删除代码的图像
public function deleteImage($image){
$filename = public_path().'/supplier/'.$image;
\File::delete($filename);
return response()->json(['message'=> 'Successfully Deleted' ]);
}