通过调用 Web 服务从 JavaScript 上传文件

发布于 2024-10-15 23:46:30 字数 3668 浏览 2 评论 0原文

我有以下允许我上传文件的 Web 服务:

[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.

我怎样才能避免这个错误?

谢谢,问候。

I have the following web service that allows me uploading files:

[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();
            }
        }
    }

It works great when it gets invoked from my Windows form.

Now, I'm trying to make it work with HTML/JavaScript. The index.html file is put on the server side (to avoid the cross-domain error) and contains the following code:

<!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>

When I try to upload a file, I get the following response from the server:

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

How can I avoid this error?

Thanks, regards.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁与争疯 2024-10-22 23:46:31

我不知道这个例子是否对你有帮助,但我让它与 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();
}

I dont know if this example will help you, but I got it working with jQuery 1.4 like this:

//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();
}
软糯酥胸 2024-10-22 23:46:30

您无法使用 Ajax 上传文件。您可以使用模拟类似效果的 iframe,但您仍然需要提交表单。 (通过 $("form").submit(); 或单击提交按钮)

You can't upload a file with Ajax. You can use an iframe which simulates a similiar effect, but you still have to sumbit the form. (by $("form").submit(); or clicking the submit button)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文