I have the following problem when I use file upload. Ajax executes "at the same time" the two actions. And I would like him to perform the ulpoad action and then the other. Or another way to upload.
<div class="editor-field">
<input type="file" name="file" id="file" />
@Html.HiddenFor(model=>model.FotoVitrine)
@Html.ValidationMessageFor(model => model.FotoVitrine)
</div>
<button type="button" onclick="postUpload('/CMS/Produto/Create', '/CMS/Produto/Index');" class="btn btn-success">Salvar</button>
function postUpload(post, redirect) {
uploadfile();
OpenPost(post, redirect);
}
function uploadfile() {
var img = $("#file").val();
if (img) {
var file = document.getElementById('file').files[0];
var formData = new FormData();
formData.append(file.name, file);
var xhr = new XMLHttpRequest();
var url = "/Produto/UploadArquivo";
xhr.open('POST', url, true);
xhr.onload = function (e) {
var response = $.parseJSON(e.target.response);
console.log(response.fileName);
alert(response.fileName);
$("#FotoVitrine").val(response.fileName);
};
xhr.send(formData);
}
}
function OpenPost(url, redirect) {
if ($("form").valid()) {
var form = $("form").serialize();
$('#Conteudo').empty().append('<div id="loader"><img src="/Content/Images/loading.gif"/></div>');
$.ajax({
type: "POST",
url: url,
data: form,
success: function (response) {
Open(redirect);
}
});
}
}
function Open(url, redirect) {
$('#Conteudo').empty().append('<div id="loader"><img src="/Content/Images/loading.gif"/></div>');
$.get(url, function (response) {
if (redirect)
Open(redirect);
$('#Conteudo').html(response);
$('#loader').remove();
});
}
[AcceptVerbs(HttpVerbs.Post)]
public void UploadArquivo()
{
HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;
if (file != null && file.ContentLength > 0)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("server" + file.FileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "pass");
request.UsePassive = false;
byte[] fileContents = new byte[file.ContentLength];
file.InputStream.Position = 0;
file.InputStream.Read(fileContents, 0, file.ContentLength);
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
}
[AcceptVerbs(HttpVerbs.Post), ValidateInput(false)]
public PartialViewResult Create(FormCollection collection)
{
var bdprodutos = Loja_ProdutosAplicacaoConstrutor.Loja_ProdutosAplicacaoEF();
var produto = new Loja_Produtos();
produto.FotoVitrine = collection["FotoVitrine"];
(...)
return null;
}