Загрузка файла из JavaScript с помощью веб-службы - PullRequest
3 голосов
/ 07 февраля 2011

У меня есть следующий веб-сервис, который позволяет загружать файлы:

[WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // Pour autoriser l'appel de ce service Web depuis un script à l'aide d'ASP.NET AJAX, supprimez les marques de commentaire de la ligne suivante. 
    [System.Web.Script.Services.ScriptService]
    public class Upload : System.Web.Services.WebService
    {
        [WebMethod]
        public bool UploadFile(string PictureName, byte[] PictureStream)
        {
            FileStream fileStream = null;
            BinaryWriter writer = null;
            string filePath;

            try
            {
                filePath = HttpContext.Current.Server.MapPath(".") + ConfigurationManager.AppSettings["PictureUploadDirectory"] + PictureName;

                if (PictureName != string.Empty)
                {
                    fileStream = File.Open(filePath, FileMode.Create);
                    writer = new BinaryWriter(fileStream);
                    writer.Write(PictureStream);
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                if (fileStream != null)
                    fileStream.Close();
                if (writer != null)
                    writer.Close();
            }
        }
    }

Отлично работает, когда вызывается из моей формы Windows.

Теперь я пытаюсь заставить его работать с HTML / JavaScript. Файл index.html размещается на стороне сервера (во избежание междоменной ошибки) и содержит следующий код:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/themes/base/jquery-ui.css" type="text/css" media="all" /> 
        <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" /> 
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 
        <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#btnSend").click(function () {
                    var fileStream = $("#fileToSend").val();
                    $.ajax({
                        type: "POST",
                        data: { PictureName: 'foobar', PictureStream: fileStream },
                        dataType: "image/gif",
                        url: "http://localhost/WebServices/Upload.asmx/UploadFile",
                        contentType: "application/x-www-form-urlencoded",
                        success: function () {
                            alert('yes');
                        },
                        error: function () {
                            alert('bouh');
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <input type="file" id="fileToSend"/>
        <br />
        <input type="button" value="Envoyer" id="btnSend"/>
    </body>
</html>

Когда я пытаюсь загрузить файл, я получаю следующий ответ от сервера:

System.ArgumentException: Unable to convert C:\fakepath\logo.gif into System.Byte.

Как мне избежать этой ошибки?

Спасибо, привет.

Ответы [ 2 ]

1 голос
/ 07 февраля 2011

Вы не можете загрузить файл с помощью Ajax.Вы можете использовать iframe, который имитирует похожий эффект, но вам все равно придется добавить форму.($("form").submit(); или нажатием кнопки отправки)

0 голосов
/ 30 сентября 2015

Я не знаю, поможет ли вам этот пример, но я работал с jQuery 1.4 следующим образом:

//JAVASCRIPT

    var objFile = $jQuery("#fileToUpload");
    var file = objFile[0].files[0];
    API.call({
        url : "rest-url/upload",
        type : "POST",
        contentType : "multipart/form-data",
        data: file,
        processData: false
    }); 

//JAVA

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("rest-url/upload")
public Response upload(InputStream fileInputStream) throws Exception {
    //here you got your file
    return Response.ok().entity(new Object("response")).build();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...