Estou com o seguinte problema quando utilizo o upload de arquivo. O ajax executa "ao mesmo tempo" as duas actions. E gostaria que ele executasse a action de ulpoad e depois a outra. Ou então uma outra maneira de fazer o 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;
}