我正在尝试通过VueJs和Laravel更新图像变量,很遗憾,我无法这样做。
这是结果问题:
Request URL: http://dashboard.test/api/services/1
Request Method: PUT
Status Code: 422 Unprocessable Entity
Remote Address: 127.0.0.1:80
Referrer Policy: no-referrer-when-downgrade
似乎所有内容均已正确上传,但图像变量未读取,如在原始数据上所示:
{image: {}, name: "1232",…}
description: "Provide a complete analysis of the project by a suitable methodology for the project."
image: {}
name: "1232"
处理上传表单的模板的快照
<form @submit.prevent="onSubmit" enctype="multipart/form-data" v-else>
<div class="form-group">
<label for="input-1">Image</label>
<img :src="'/images/services/'+service.image">
<input type="file" name="image" class="form-control"
accept="image" v-on:change="onImageChange">
</div>
<div class="form-group">
<label for="input-2">Name</label>
<input type="text" name="name" class="form-control" id="input-2"
placeholder="Enter Skill Name" v-model="service.name">
</div>
<div class="form-group">
<label for="input-3">Description</label>
<textarea name="description" class="form-control" id="input-3" placeholder="Enter Skill Description" v-model="service.description"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary px-5"><i class="icon-lock"></i> Register</button>
</div>
</form>
负责上述形式的VueJs脚本:
export default {
data() {
return {
message: null,
loaded: false,
saving: false,
service: {
id: null,
name: "",
image: "",
description: ""
}
};
},
methods: {
onImageChange(e){
console.log(e.target.files[0]);
this.image = e.target.files[0];
},
onSubmit(e) {
e.preventDefault();
let currentObj = this;
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
let formData = new FormData();
formData.append('image', this.image);
this.saving = true;
api.update(this.service.id,
{
image: this.service.image,
name: this.service.name,
description: this.service.description,
},
).then((response) => {
this.message = 'service updated';
setTimeout(() => this.message = null, 500);
this.service = response.data.data;
}).catch(error => {
console.log(error)
}).then(_ => this.saving = false);
}
ServicesController文件,它负责执行后端操作:
public function update(Service $service, Request $request)
{
$data = $request->validate([
'image' => 'required',
'name' => 'required',
'description' => 'required',
]);
if ($request->file('image')->isValid()) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = 'storage/images/services/' ;
$file->move($destinationPath,$fileName);
$service->image = $fileName;
}
$service->save();
$service->update($data);
}
我认为问题是当我打开检查元素并更改图像时,它会更改图像变量
<img data-v-41680f60="" src="/images/services/analysis.png">
至
<img data-v-41680f60="" src="/images/services/[object File]">
我不知道[目标文件]的来源,并且为什么不能正常工作,因为当我尝试创建新服务时,它工作得很好。它只是在更新部分变得不稳定。