modifica dati azienda, create e edit per upload logo

This commit is contained in:
michele 2025-10-03 12:40:48 +02:00
parent fb49116bba
commit 0f7665b761
3 changed files with 135 additions and 159 deletions

View File

@ -91,100 +91,83 @@ namespace VirtualTask.Controllers
} }
[HttpPost] [HttpPost]
public IActionResult Create(DatiAzienda model) public async Task<IActionResult> Create(DatiAzienda model)
{ {
DatiAziendaTable dat=new DatiAziendaTable();
SessionHelper helper = new SessionHelper(this); SessionHelper helper = new SessionHelper(this);
admin = helper.GetStringValue("admin"); string token = helper.GetStringValue("tok");
token = helper.GetStringValue("tok"); string tenant2 = helper.GetStringValue("tenant2"); // tenant = azienda
tenant = helper.GetStringValue("tenant");
tenant2 = helper.GetStringValue("tenant2"); string apiUrl = helper.GetStringValue("apiUrl");
string admin = helper.GetStringValue("admin");
ViewBag.Admin = admin; ViewBag.Admin = admin;
if (model.logo != null) ViewBag.AllTecnici = getTecnici();
{
string pic = System.IO.Path.GetFileName(model.logo.FileName);
//2025-05-05: gestione directory iommagine nel caso che l'azienda sia più corta di 5 caratteri
string dir = tenant2;
if (!string.IsNullOrEmpty(tenant2) && tenant2.Trim().Length < 5)
{
dir = tenant2.Trim();
}
string path = string.Format("{0}{1}\\{2}",_pathLoghi, dir, pic);
//string projectRootPath = _hostingEnvironment.ContentRootPath;
//// file is uploaded if (!ModelState.IsValid)
using (Stream fileStream = new FileStream(path, FileMode.Create)) return View(model);
string logoUrl = null;
// 1⃣ Upload del logo tramite API UploadLogo
// 1⃣ Upload del logo tramite API UploadLogo
if (model.logo != null && model.logo.Length > 0)
{ {
model.logo.CopyToAsync(fileStream); // ✅ Token nella query string
string uploadUrl = $"{apiUrl}datiazienda/upload_logo?token={token}";
using (var httpClient = new HttpClient())
using (var form = new MultipartFormDataContent())
{
// ⚡ Solo il file nel multipart
var fileContent = new StreamContent(model.logo.OpenReadStream());
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(
string.IsNullOrWhiteSpace(model.logo.ContentType) ? "application/octet-stream" : model.logo.ContentType
);
form.Add(fileContent, "file", model.logo.FileName);
HttpResponseMessage response = await httpClient.PostAsync(uploadUrl, form);
if (!response.IsSuccessStatusCode)
{
string err = await response.Content.ReadAsStringAsync();
ModelState.AddModelError("", "Errore upload logo: " + err);
return View(model);
} }
//// save the image path path to the database or you can send image dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
//// directly to database logoUrl = result.url;
//// in-case if you want to store byte[] ie. for DB }
using (MemoryStream ms = new MemoryStream())
}
// 2⃣ Creazione oggetto da inviare all'API datiazienda/add
var dat = new DatiAziendaTable
{ {
model.logo.CopyTo(ms); azienda = tenant2,
byte[] array = ms.GetBuffer(); tecnico = model.tecnico,
dat.logo = array; ragsoc = model.ragsoc,
} testo_buono = model.testo_buono,
dat.azienda = tenant2; url_logo = logoUrl,
dat.testo_buono = model.testo_buono; logo = model.logo != null ? await ConvertToByteArrayAsync(model.logo) : null
dat.url_logo = string.Format("{0}{1}/{2}", _urlLoghi, dir, pic); };
dat.ragsoc = model.ragsoc;
dat.tecnico = model.tecnico;
}
apiUrl = helper.GetStringValue("apiUrl");
admin = helper.GetStringValue("admin");
ViewBag.Admin = admin;
urlBase = apiUrl + "datiazienda/add";
urlBase = urlBase + "?token=" + token;
Uri baseAddress = new Uri(urlBase);
client = new HttpClient();
client.BaseAddress = baseAddress;
// 3⃣ Invio dati all'API datiazienda/add
string apiAddUrl = apiUrl + "datiazienda/add?token=" + token;
using (var httpClient = new HttpClient())
{
string data = JsonConvert.SerializeObject(dat); string data = JsonConvert.SerializeObject(dat);
StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; HttpResponseMessage saveResponse = await httpClient.PostAsync(apiAddUrl, content);
if (response.IsSuccessStatusCode) if (!saveResponse.IsSuccessStatusCode)
{ {
//prima di andare alla pagina devo chiamare il metodo per string err = await saveResponse.Content.ReadAsStringAsync();
//salvare il file in locale in modo che sia visibile sul web dall'app ModelState.AddModelError("", "Errore salvataggio dati: " + err);
//C:\ZAPIPOLO\loghi return View(model);
//https://api.poloinformatico.it:9000/api/Polo/datiazienda/saveFile?azienda=AZI02&tecnico=aaaaa%20%20%20%20%20%20%20%20%20%20&pathSrv=C%3A%5CZAPIPOLO%5Cloghi' }
apiUrl = helper.GetStringValue("apiUrl"); }
urlBase = apiUrl + "datiazienda/savefile";
urlBase = urlBase + "?azienda=" + model.azienda;
urlBase = urlBase + "&tecnico=" + model.tecnico;
//urlBase = urlBase + "&pathSrv=" + "C:\\ZAPIPOLO\\loghi";
urlBase = urlBase + "&pathSrv=" + _pathLoghi;
baseAddress = new Uri(urlBase);
client = new HttpClient();
client.BaseAddress = baseAddress;
HttpResponseMessage response2 = client.GetAsync(baseAddress).Result;
if (response2.IsSuccessStatusCode)
{
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
else
{
errMes = response.Content.ReadAsStringAsync().Result;
helper.SetStringValue("errMsg", errMes);
return RedirectToAction("Error");
}
}
else
{
errMes = response.Content.ReadAsStringAsync().Result;
helper.SetStringValue("errMsg", errMes);
return RedirectToAction("Error");
}
}
#endregion CREATE #endregion CREATE
@ -228,103 +211,72 @@ namespace VirtualTask.Controllers
} }
[HttpPost] [HttpPost]
public IActionResult Edit(DatiAziendaTable model) public async Task<IActionResult> Edit(DatiAziendaTable model)
{ {
SessionHelper helper = new SessionHelper(this); SessionHelper helper = new SessionHelper(this);
token = helper.GetStringValue("tok"); string token = helper.GetStringValue("tok");
tenant = helper.GetStringValue("tenant"); string tenant2 = helper.GetStringValue("tenant2");
tenant2 = helper.GetStringValue("tenant2");
if (string.IsNullOrEmpty(token)) if (string.IsNullOrEmpty(token))
{
return RedirectToAction("Login2", "Login"); return RedirectToAction("Login2", "Login");
}
//model.azienda = tenant;
if(model.logo2!=null)
{
string pic = System.IO.Path.GetFileName(model.logo2.FileName);
//2025-05-05: gestione directory iommagine nel caso che l'azienda sia più corta di 5 caratteri string apiUrl = helper.GetStringValue("apiUrl");
string dir = tenant2;
if (!string.IsNullOrEmpty(tenant2) && tenant2.Trim().Length < 5)
{
dir = tenant2.Trim();
}
string path = string.Format("{0}{1}\\{2}", _pathLoghi, dir, pic);
//string projectRootPath = _hostingEnvironment.ContentRootPath;
//// file is uploaded // 1⃣ Upload del logo tramite API UploadLogo
using (Stream fileStream = new FileStream(path, FileMode.Create)) if (model.logo2 != null && model.logo2.Length > 0)
{ {
model.logo2.CopyToAsync(fileStream); string uploadUrl = $"{apiUrl}datiazienda/upload_logo?token={token}";
using (var httpClient = new HttpClient())
using (var form = new MultipartFormDataContent())
{
var fileContent = new StreamContent(model.logo2.OpenReadStream());
fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(
string.IsNullOrWhiteSpace(model.logo2.ContentType) ? "application/octet-stream" : model.logo2.ContentType
);
form.Add(fileContent, "file", model.logo2.FileName);
HttpResponseMessage response = await httpClient.PostAsync(uploadUrl, form);
if (!response.IsSuccessStatusCode)
{
string err = await response.Content.ReadAsStringAsync();
ModelState.AddModelError("", "Errore upload logo: " + err);
return View(model);
} }
//// save the image path path to the database or you can send image dynamic result = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
//// directly to database model.url_logo = result.url;
//// in-case if you want to store byte[] ie. for DB }
// Salvo i byte del file nel modello se serve per il DB
using (MemoryStream ms = new MemoryStream()) using (MemoryStream ms = new MemoryStream())
{ {
model.logo2.CopyTo(ms); await model.logo2.CopyToAsync(ms);
byte[] array = ms.GetBuffer(); model.logo = ms.ToArray();
model.logo = array;
} }
model.logo2 = null; model.logo2 = null;
model.url_logo = string.Format("{0}{1}/{2}", _urlLoghi, dir, pic);
} }
// 2⃣ Invio dati all'API datiazienda/mod
apiUrl = helper.GetStringValue("apiUrl"); string modUrl = $"{apiUrl}datiazienda/mod?token={token}";
urlBase = apiUrl + "datiazienda/mod"; using (var client = new HttpClient())
urlBase = urlBase + "?token=" + token; {
Uri baseAddress = new Uri(urlBase);
client = new HttpClient();
client.BaseAddress = baseAddress;
string data = JsonConvert.SerializeObject(model); string data = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(data, Encoding.UTF8, "application/json"); StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(baseAddress, content).Result; HttpResponseMessage response = await client.PostAsync(modUrl, content);
if (response.IsSuccessStatusCode) if (!response.IsSuccessStatusCode)
{ {
//prima di andare alla pagina devo chiamare il metodo per string errMes = await response.Content.ReadAsStringAsync();
//salvare il file in locale in modo che sia visibile sul web dall'app helper.SetStringValue("errMsg", errMes);
//C:\ZAPIPOLO\loghi return RedirectToAction("Error");
//https://api.poloinformatico.it:9000/api/Polo/datiazienda/saveFile?azienda=AZI02&tecnico=aaaaa%20%20%20%20%20%20%20%20%20%20&pathSrv=C%3A%5CZAPIPOLO%5Cloghi' }
apiUrl = helper.GetStringValue("apiUrl");
urlBase = apiUrl + "datiazienda/savefile";
if(!string.IsNullOrEmpty(model.azienda) && model.azienda.Length<5)
{
model.azienda= model.azienda.Trim();
} }
urlBase = urlBase + "?azienda=" + model.azienda;
urlBase = urlBase + "&tecnico=" + model.tecnico.Trim();
urlBase = urlBase + "&pathSrv=" + _pathLoghi;
baseAddress = new Uri(urlBase);
client = new HttpClient();
client.BaseAddress = baseAddress;
data = JsonConvert.SerializeObject(model);
content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage response2 = client.PostAsync(baseAddress, content).Result;
if (response2.IsSuccessStatusCode)
{
return RedirectToAction("Index"); return RedirectToAction("Index");
} }
else
{
errMes = response2.Content.ReadAsStringAsync().Result;
helper.SetStringValue("errMsg", errMes);
return RedirectToAction("Error");
}
}
else
{
errMes = response.Content.ReadAsStringAsync().Result;
helper.SetStringValue("errMsg", errMes);
return RedirectToAction("Error");
}
}
#endregion #endregion
#region DETAIL #region DETAIL
@ -435,7 +387,7 @@ namespace VirtualTask.Controllers
} }
#endregion DELETE #endregion DELETE
#region ALTRI METODI
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error() public IActionResult Error()
{ {
@ -443,6 +395,7 @@ namespace VirtualTask.Controllers
string e = helper.GetStringValue("errMsg"); string e = helper.GetStringValue("errMsg");
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrMsg = e }); return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier, ErrMsg = e });
} }
private List<SelectListItem> getTecnici() private List<SelectListItem> getTecnici()
{ {
SessionHelper helper = new SessionHelper(this); SessionHelper helper = new SessionHelper(this);
@ -480,5 +433,27 @@ namespace VirtualTask.Controllers
} }
return selectItems; return selectItems;
} }
// Metodo helper per convertire IFormFile in byte[]
private async Task<byte[]> ConvertToByteArrayAsync(IFormFile file)
{
using (var ms = new MemoryStream())
{
await file.CopyToAsync(ms);
return ms.ToArray();
} }
} }
#endregion ALTRI METODI
// Classe per deserializzare la risposta JSON dell'API
private class UploadResponse
{
public string? message { get; set; }
public string? url { get; set; }
public string? fileName { get; set; }
}
}
}

View File

@ -60,9 +60,7 @@
<input type="submit" value="Elimina" class="agy-btn submitForm" /> <input type="submit" value="Elimina" class="agy-btn submitForm" />
<input type="hidden" id="azienda" value=@Html.DisplayFor(model => model.azienda) name="azienda" /> <input type="hidden" id="azienda" value=@Html.DisplayFor(model => model.azienda) name="azienda" />
<input type="hidden" id="tecnico" value=@Html.DisplayFor(model => model.tecnico) name="tecnico" /> <input type="hidden" id="tecnico" value=@Html.DisplayFor(model => model.tecnico) name="tecnico" />
<div> <a asp-action="Index" value="Torna alla lista" class="agy-btn submitForm">Torna alla lista</a>
<a asp-action="Index">Torna alla lista</a>
</div>
</form> </form>
</div> </div>
</div> </div>

View File

@ -7,10 +7,12 @@
}, },
"ApplicationInsights": { "ApplicationInsights": {
////PRODUZIONE //PRODUZIONE
"rootUrlApi": "https://api-vt.poloinformatico.it/api/Polo/", "rootUrlApi": "https://api-vt.poloinformatico.it/api/Polo/",
"rootUrlApi2": "https://api-vt.poloinformatico.it/VIRTU/", "rootUrlApi2": "https://api-vt.poloinformatico.it/VIRTU/",
"rootWebLoghi": "C:\\ZAPIPOLO\\api_polo\\wwwroot\\VIRTU\\", //"rootWebLoghi": "C:\\ZAPIPOLO\\api_polo\\wwwroot\\VIRTU\\",
//"rootWebLoghi": "/zucchetti/api/api-vt.poloinformatico.it/app/wwwroot/VIRTU/",
"rootWebLoghi": "./wwwroot/VIRTU",
"rootUrl": "https://virtualtask.it/", "rootUrl": "https://virtualtask.it/",
"rootPath": "/mnt/storagebox", "rootPath": "/mnt/storagebox",
@ -20,10 +22,11 @@
//"rootWebLoghi": "C:\\Users\\audif\\source\\repos\\VirtualTask\\wwwroot\\VIRTU\\", //"rootWebLoghi": "C:\\Users\\audif\\source\\repos\\VirtualTask\\wwwroot\\VIRTU\\",
//"rootUrl": "https://localhost:7140/", //"rootUrl": "https://localhost:7140/",
//MICHELE: PUNTAMENTO A MIO PC PER FARE I TEST ////MICHELE: PUNTAMENTO A MIO PC PER FARE I TEST
//"rootUrlApi": "https://localhost:7068/api/Polo/", //"rootUrlApi": "https://localhost:7068/api/Polo/",
//"rootUrlApi2": "https://localhost:7068//VIRTU/", //"rootUrlApi2": "https://localhost:7068//VIRTU/",
//"rootWebLoghi": "C:\\Users\\audif\\source\\repos\\VirtualTask\\wwwroot\\VIRTU\\", ////"rootWebLoghi": "C:\\Users\\audif\\source\\repos\\VirtualTask\\wwwroot\\VIRTU\\",
//"rootWebLoghi": "/zucchetti/api/api-vt.poloinformatico.it/app/wwwroot/VIRTU/",
//"rootUrl": "https://localhost:7068/", //"rootUrl": "https://localhost:7068/",
"mittenteMail": "info@virtualtask.it", "mittenteMail": "info@virtualtask.it",