您尝试使用此编码。此图片上传代码使用前端 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);
});
});
}
这是拉威尔控制器文件编码。
$file->move(public_path('supplier'), $picture);
我们需要在 supplier 上面的代码中创建平行路径。在这个路径中应该是我们在公用文件夹中创建的Larwell文件。
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' ]);
}