使用ASP.NET中的web api将文件从客户端计算机上传到服务器时显示错误 [英] Showing error when I m uploading file from client computer to server using web api in ASP.NET

查看:90
本文介绍了使用ASP.NET中的web api将文件从客户端计算机上传到服务器时显示错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误-----

ServerUrl / api / fileupload / uploadfile。交叉源请求仅支持协议方案:http,数据,chrome,chrome扩展,https,chrome-extension-resource。







 <%@     Page    语言  =  C#    AutoEventWireup   =  true    CodeBehind   =  FileUplodaTest.aspx.cs   继承  =  UploadFileWebApi.FileUplodaTest   %>  

< !DOCTYPE html >

< html xmlns = http://www.w3.org/1999/xhtml >
< head runat = server >
< title > < / title >
< script src = // ajax .googleapis.com / ajax / libs / jquery / 2.1.1 / jquery.min.js > < / script >

< script 类型 = text / javascript >
$( document )。ready( fun ction (){

$(' #btnUploadFile' ).on(' 点击'功能(){

var data = new FormData();

var files = $( #fileUpload)。get( 0 )。files;

// 将上传的图像内容添加到表单数据集
if (files.length> 0 ){
data.append( UploadedImage,files [ 0 ]);
}

// 使用contentType = false和procesDate生成Ajax请求= false
var ajaxRequest = $ .ajax({
type: POST
url: ServerUrl / api / fileupload / uploadfile
contentType: false
processData: false
data:data
});

ajaxRequest.done( function (xhr,textStatus){
// 执行其他操作
alert( File Uploaded Sucessfull !!);
});
});
});
< / script >


< / head >
< 正文 >
< 表单 id = form1 runat = 服务器 >
< div >
< div >
< label for = fileUpload >
选择要上传的文件:< / label >
< 输入 id = fileUpload type = file / >

< input id = btnUploadFile type = < span class =code-keyword> button
value = 上传文件 / >

< / div >

< / div >
< / form >
< / body >
< / html >














和网络Api控制器代码在这里:----





< br $> b $ b



 使用系统; 
使用 System.Collections.Generic;
使用 System.IO;
使用 System.Linq;
使用 System.Net;
使用 System.Net.Http;
使用 System.Web;
使用 System.Web.Http;

命名空间 UploadFileWebApi.Controllers
{
public class FileUploadController:ApiController
{
[HttpPost]
public < span class =code-keyword> void UploadFile()
{
if (HttpContext.Current.Request.Files。 AllKeys.Any())
{
// 从Files集合中获取上传的图像
var httpPostedFile = HttpContext.Current.Request.Files [ UploadedImage];
string pathA = D://下载;
if (httpPostedFile!= null
{
// 验证上传的图像(可选)

// 获取完整的文件路径
// var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath(〜/ UploadedFiles),httpPostedFile.FileName);
var fileSavePath = Path.Combine(pathA,httpPostedFile.FileName);

// 将上传的文件保存到UploadedFiles文件夹
httpPostedFile.SaveAs(fileSavePath);
}
}
}
}
}











当我在我的本地服务器上测试这个Web服务时,这工作正常但是当我在服务器上托管这个web api并使用它来调用它时jquery Ajax调用(POST)FROM我的消费者应用程序这个错误显示在控制台中。所以请帮我如何从客户端上传文件到服务器以及如何解决这个问题。



我尝试了什么:



当我在我的本地服务器上测试此Web服务时,这样可以正常工作但是当我主持时这个web api在服务器上并使用jquery Ajax调用(POST)FROM我的消费者应用程序调用它这个错误显示在控制台中。所以请帮我如何从客户端上传文件到服务器以及如何解决这个问题。

解决方案

document )。ready( function () {

' #btnUploadFile')。on( 点击 function (){

var data = new FormData();

var files =


#fileUpload)。get( 0 )。files;

// 将上传的图像内容添加到表单数据集
if (files.length> 0 ){
data.append( UploadedImage,files [ 0 ]);
}

// 使用contentType = false和procesDate生成Ajax请求= false
var ajaxRequest =


this is the error -----
ServerUrl/api/fileupload/uploadfile. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.



<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUplodaTest.aspx.cs" Inherits="UploadFileWebApi.FileUplodaTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function () {

            $('#btnUploadFile').on('click', function () {

                var data = new FormData();

                var files = $("#fileUpload").get(0).files;

                // Add the uploaded image content to the form data collection
                if (files.length > 0) {
                    data.append("UploadedImage", files[0]);
                }

                // Make Ajax request with the contentType = false, and procesDate = false
                var ajaxRequest = $.ajax({
                    type: "POST",
                    url: "ServerUrl/api/fileupload/uploadfile",
                    contentType: false,
                    processData: false,
                    data: data
                });

                ajaxRequest.done(function (xhr, textStatus) {
                    // Do other operation
                    alert("File Uploaded Sucessfull !!");
                });
            });
        });
    </script>


</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div>
                <label for="fileUpload">
                    Select File to Upload:</label>
                <input id="fileUpload" type="file" />

                <input id="btnUploadFile" type="button" value="Upload File" />

            </div>

        </div>
    </form>
</body>
</html>








and Web Api Controller Code is Here :----





using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace UploadFileWebApi.Controllers
{
    public class FileUploadController : ApiController
    {
        [HttpPost]
        public void UploadFile()
        {
            if (HttpContext.Current.Request.Files.AllKeys.Any())
            {
                // Get the uploaded image from the Files collection
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
                string pathA = "D://Download";
                if (httpPostedFile != null)
                {
                    // Validate the uploaded image(optional)

                    // Get the complete file path
                    //var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
                    var fileSavePath = Path.Combine(pathA, httpPostedFile.FileName);

                    // Save the uploaded file to "UploadedFiles" folder
                    httpPostedFile.SaveAs(fileSavePath);
                }
            }
        }
    }
}






When i am Testing this web service on my local server this is work fine but when i host this web api on server and call it using jquery Ajax call(POST) FROM My consumer application this this error is showing in console .so please help me how to upload file from client to server and how to resolve this problem.

What I have tried:

When i am Testing this web service on my local server this is work fine but when i host this web api on server and call it using jquery Ajax call(POST) FROM My consumer application this this error is showing in console .so please help me how to upload file from client to server and how to resolve this problem.

解决方案

(document).ready(function () {


('#btnUploadFile').on('click', function () { var data = new FormData(); var files =


("#fileUpload").get(0).files; // Add the uploaded image content to the form data collection if (files.length > 0) { data.append("UploadedImage", files[0]); } // Make Ajax request with the contentType = false, and procesDate = false var ajaxRequest =


这篇关于使用ASP.NET中的web api将文件从客户端计算机上传到服务器时显示错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆