[英]File Object - Renaming a file name in a state react
當我嘗試重命名一個已經在 state 中的文件時遇到了一個問題。我遇到了一個問題,它將替換所有文件信息並添加我更改的名稱,當我將它發送到要保存的服務器它不能,因為它只有一個字符串名稱而不是文件信息。 這是代碼:
constructor(props){
super(props);
this.state = {
images: {
iconImage: null,
}
}
}
onIconChange = (event) => {
console.log(event.target.files[0]);
this.setState({images: {iconImage: event.target.files[0]}});
}
onSubmit = (isNew) => {
if(this.state.images.iconImage){
this.setState({images: {iconImage: {
name: `${this.state.name}-${this.state.images.iconImage.name}`
}}},
this.sendImage);
}
else{
this.reset();
}
}
sendImage = () => {
const data = new FormData();
console.log(this.state.images.iconImage);
data.append('image', this.state.images.iconImage);
axios({
url: 'http://127.0.0.1:3002/icon',
method: 'post',
data: data,
body: JSON.stringify({
vID: this.state.id
})
})
.then(res => console.log(res.data))
.catch(err => console.error(`error posting image: ${err}`));
this.reset();
}
更名前:文件 {name: "CoverImage.JPG", lastModified: 1617527811701, lastModifiedDate: Sun Apr 04 2021 19:16:51 GMT+1000(澳大利亞東部標准時間),webkitRelativePath: "", size: 74957, …}
改名后:{name: "test2-CoverImage.JPG"}
所有文件屬性都是只讀屬性。 因此,您也不能使用spread operator
或Object.assign
更新那些。
但是,您可以使用以下代碼重命名文件。
const myNewFile = new File(
[this.state.images.iconImage],
`${this.state.name}-${this.state.images.iconImage.name}`,
{ type: this.state.images.iconImage.type }
);
this.setState(
{
images: {
iconImage: myNewFile
}
},
() => {
console.log(this.state.images);
console.log(this.state.images.iconImage.name);
console.log(this.state.images.iconImage.size);
}
);
}
好的,出於某種原因您無法編輯文件名,但是有一個解決方法。 所需要做的就是在新變量中創建一個新文件。 這是我的做法:
const mynewFile = new File([this.state.images.iconImage],
`${this.state.name}-${this.state.images.iconImage.name}`);
這是我在這里找到答案的網站的鏈接。 再次嘗試設置 state 要簡單得多!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.