我正在尝试通过API使用vuejs和laravel上传图像。在vue.js中,我通过api将图像信息发送到laravel。但是laravel无法以正确的格式获取信息。这就是为什么它显示错误。可能是我的程序不正确。
这是我的密码
Vue.js代码
`
<input type="file" accept="image/*" @change="doctorImageSelected(event)">
<button style="float: left;" class="ajmal-custom-btn" @click="goToUploadImage()">Upload</button>
`
`
doctorImageSelected (event) {
let image = event.target.files[0]
this.image = image
// console.log(this.image)
let reader = new FileReader();
reader.readAsDataURL(image);
reader.onload = event => {
this.image = event.target.result
}
},
goToUploadImage(){
var self = this
this.$http.post(apiDomain + 'api/savePatientProfilePicture',{pic: self.image,id: self.id})
.then(response => {
if(response.status === 200){
console.log(response)
}
}).catch((e) => {
console.log(e)
})
}
`
Laravel代码
`
public function savePatientProfilePicture(Request $request){
$pictureInfo = $request->pic;
$picName = $request->id . $pictureInfo->getClientOriginalName();
return $picName;
$folder = "patinetImage/";
$pictureInfo->move($folder,$picName);
$picUrl = $folder.$picName;
$user = new User();
$patientPic = User::find($request->id);
$patientPic->image = $picUrl;
$patientPic->save();
}
`
错误
在字符串上调用成员函数
getClientOriginalName()
答案 0 :(得分:2)
确保已将Content-Type: application/x-www-form-urlencoded
添加到请求标头中。
然后,尝试以下代码
goToUploadImage(){
var formData = new FormData;
formData.append("pic", this.image, this.name);
formData.append("id", this.id);
var self = this
this.$http.post(apiDomain + 'api/savePatientProfilePicture',formData, {
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(response => {
if(response.status === 200){
console.log(response)
}
}).catch((e) => {
console.log(e)
})
}
答案 1 :(得分:1)
如果要获取文件的原始名称,则需要在UploadedFile对象上调用它
$pictureInfo = $request->file('pic');
$picName = $request->id . $pictureInfo->getClientOriginalName();
您可以使用ref
和fetch
api
<input type="file" accept="image/*" @change="doctorImageSelected()" ref="doctorImage" />
<button style="float: left;" class="ajmal-custom-btn" @click="goToUploadImage()">Upload</button>
在Java语言中
export default {
data() {
return {
image: {},
id: 1 // Your ID and rest of data here
};
},
methods: {
doctorImageSelected(event) {
this.image = this.$refs.doctorImage.files[0];
},
goToUploadImage() {
var fd = new FormData();
fd.append("pic", this.image);
fd.append("id", this.id);
fetch(`${apiDomain}api/savePatientProfilePicture`, {
headers: {
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": document.querySelector('meta[name="csrf-token"]')
.content
},
method: "POST",
credentials: "same-origin",
body: fd
})
.then(response => {
if (response.status === 200) {
console.log(response);
}
})
.catch(e => {
console.log(e);
});
}
}
};
希望这会有所帮助