Подскажите как можно передать файл в веб сервис
/**
* ########## ####### ###### #####.
* @private
* @param {Object} files #####, ############ FileAPI
*/
onFileSelect: function(files) {
this.console.log(files)
if (files && files.length) {
const file = files[0];
const reader = new FileReader();
reader.onload = () => {
const fileData = reader.result; // содержимое файла
this.console.log(fileData)
this.console.log(file)
const blob = new Blob([fileData], { type: file.type });
this.callDownloadSupplyPlanService(file, blob, file.name)
}
reader.readAsArrayBuffer(file); // читаем содержимое файла
}
},После того как выбрал файл пытаюсь сформировать запрос к своему сервису(пытплся передавать formdata, пытался просто file)
callDownloadSupplyPlanService: function(file, fileData, fileName) {
if (fileData) {
const requestUrl = `${Terrasoft.workspaceBaseUrl}/rest/HaleonReportWebService/DownloadSupplyPlan`;
const formData = new FormData();
formData.append('file', fileData, fileName);
Terrasoft.AjaxProvider.request({
url: requestUrl,
method: "POST",
data: file,
processData: false,
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
callback: function() {
this.console.log(arguments);
},
scope: this
});
}
},код метода , к которому обращаюсь
На вход принимаю стрим, но почему то он всегда приходит 0 байт, может я делаю что то не так?
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public string DownloadSupplyPlan(Stream stream)
{
SessionHelper.SpecifyWebOperationIdentity(HttpContextAccessor.GetInstance(),
SystemUserConnection.CurrentUser);
try
{
using (var reader = new StreamReader(stream))
{
var content = reader.ReadToEnd();
return $"Received content length: {content.Length}";
}
}
catch(Exception e)
{
// обрабатываем ошибку
return $"Error: {e.Message}";
}
}
Нравится
Проведите, пожалуйста, такой тест не в бизнес время:
1) Найдите системную настройку с кодом "ActiveFileContentStorage"
2) Убедитесь, что в ней значение "Database", если нет, то сохраните где-то текущее значение, проставьте "Database" и перелогиньтесь
3) Загрузите новый файл в систему
4) Попробуйте подход выше на новом файле
На этом моменте нужен результат.
5) Вернитесь в настройку с кодом "ActiveFileContentStorage"
6) Проставьте значение, которое забекапили на пункте 2
7) Перелогиньтесь
Пока что подозрение на то, что сайт интегрирован с файловым хранилищем и из-за этого контент пустой.
решил через
XMLHttpRequest запрос
callDownloadSupplyPlanService: function(fileData) {
if (fileData) {
const csrfToken = this.getBpmCsrfToken();
const requestUrl = `${Terrasoft.workspaceBaseUrl}/rest/HaleonReportWebService/DownloadSupplyPlan`;
const xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl, true);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('BPMCSRF', csrfToken);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(fileData);
}
}