我需要将上载的.xml文件转换为String并将其发送到后端服务器。我需要保留原始的“外观”,换句话说-例如:<process.end.date>20100131</process.end.date>
,因此标记必须保留并像这样发送。如何转换文件?
uploadXML.vue
<template>
<fieldset class="buttons">
<span class="logInBTN" v-on:click="send(xml)">Send</span>
</fieldset>
<br>
<div class="mainContainer">
<table border="0px">
<tr>
<td>
<label>Upload file: </label>
<input id="fileInput" type="file" @change="handleUpload" accept=".xml"/>
</td>
</tr>
</table>
</div>
</div>
</template>
<script>
import config from '../main.js'
export default {
data(){
return {
xml: ''
}
},
methods:{
send(xml){
console.log("Result1:\n\n" + this.xml);
const url = this.$session.get('apiUrl') + 'manualReceive'
this.submit('post',url, xml);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log("manualReceive " + response.data);
if(response.data == true)
alert('Successful Sent!');
else
alert('Problem with sending message!');
})
.catch(error => {
console.log('error:' + error);
});
},
handleUpload: function(){
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var reader = new FileReader();
reader.addEventListener('load', function(){
this.xml = reader.result;
console.log("Result:\n\n" + this.xml);
});
this.xml = reader.readAsText(file);
}
}
}
</script>
更新:
我意识到xml是字符串格式。现在我知道了问题所在-当我在send(xml)函数中编写console.log("Result1:\n\n" + this.xml);
时,它是未定义的。尽管console.log("Result:\n\n" + this.xml);
可以正常工作
我该如何解决?
Update2:
<script>
import config from '../main.js'
export default {
data(){
return {
xml: ''
}
},
methods:{
send(){
/*console.log("Result2:\n\n" + this.xml);*/
const url = this.$session.get('apiUrl') + 'manualReceive'
this.submit('post',
url,
this.xml
);
},
submit(requestType, url, submitData) {
this.$http[requestType](url, submitData)
.then(response => {
console.log("manualReceive " + response.data);
if(response.data == true)
alert('Успешно изпратено съобщение към CDCO!');
else
alert('Проблем при изпращането на съобщението!');
})
.catch(error => {
console.log('error:' + error);
});
},
handleUpload: function(){
var fileInput = document.getElementById('fileInput');
var file = fileInput.files[0];
var reader = new FileReader();
var self = this;
reader.addEventListener('load', function(){
self.xml = reader.result;
/*console.log("Result1:\n\n" + self.xml);*/
});
reader.readAsText(file);
}
}
}
</script>
答案 0 :(得分:0)
您不需要将xml
传递给send
函数,因为您的xml
字符串是Vue实例的属性。将send
函数更改为此:
send(){
const url = this.$session.get('apiUrl') + 'manualReceive'
this.submit('post',url, this.xml);
}
在模板中:
<span class="logInBTN" v-on:click="send">Send</span>
更新
此外,您无需在此行中分配this.xml
:
this.xml = reader.readAsText(file);
只需使用:
reader.readAsText(file);
更新2
您在“ load”事件的函数声明中使用了function
一词,因此this
变量是FileReader。
您应该存储正确的this
或使用箭头功能:
var self = this;
reader.addEventListener('load', function(){
self.xml = reader.result;
console.log("Result:\n\n" + self.xml);
});
然后this.xml
将在发送功能中起作用。