将文件从phonegap相机上传到.Net web api

时间:2015-04-08 05:07:36

标签: angularjs cordova asp.net-web-api phonegap-plugins

服务器端

public class UploadController : ApiController
{
    public async Task<HttpResponseMessage> Post()
    {
        // Check whether the POST operation is MultiPart?
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        // Prepare CustomMultipartFormDataStreamProvider in which our multipart form
        // data will be loaded.
        string fileSaveLocation = HttpContext.Current.Server.MapPath("~/App_Data");
        CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
        List<string> files = new List<string>();

        try
        {
            // Read all contents of multipart message into CustomMultipartFormDataStreamProvider.
            await Request.Content.ReadAsMultipartAsync(provider);

            foreach (MultipartFileData file in provider.FileData)
            {
                files.Add(Path.GetFileName(file.LocalFileName));
            }

            // Send OK Response along with saved file names to the client.
            return Request.CreateResponse(HttpStatusCode.OK, files);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
}

public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

    public override string GetLocalFileName(HttpContentHeaders headers)
    {
        return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
    }
}

客户端代码,我从相机获取imageURI后将其发送到下面

 function send(imageURI) {
    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
    options.mimeType = "image/jpeg";
    options.chunkedMode = false;
    options.headers = {
        Connection: "close"
    }
    var params = {};
    params.value1 = "test";
    params.value2 = "param";
    options.params = params;
    var ft = new FileTransfer();
    ft.upload(imageURI, encodeURI("http://localhost/api/api/upload"), win, fail, options);

}

function win(r) {
    console.log("Code = " + r.responseCode);
    console.log("Response = " + r.response);
    console.log("Sent = " + r.bytesSent);
}

function fail(error) {
    alert("An error has occurred: Code = " + error.code);
    alert("upload error source " + error.source);
    alert("upload error target " + error.target);
}

我在失败功能上收到错误代码1。他们的服务器端代码有什么问题吗?我可以发送ImageURI上面写的网页api吗?

0 个答案:

没有答案