使用iOS Swift上传图片

时间:2014-09-28 07:24:53

标签: ios rest swift upload jersey

我正在尝试将图片上传到我的球衣服务器。这是我的Swift代码:

var url:NSURL = NSURL.URLWithString("http://www.quentinroussat.fr/assets/img/iOS%20icon's%20Style/ios8.png")
    var payload:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil)


    var err: NSError?
    var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)


    let endpoint: NSURL = NSURL(string: "http://localhost:8080/rest/service/Upload")
    let request = NSMutableURLRequest(URL: endpoint)
    request.HTTPMethod = "POST"


    // set Content-Type in HTTP header
    let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
    let contentType = "multipart/form-data; boundary=" + boundaryConstant
    request.HTTPBody = imageData

     request.addValue(contentType, forHTTPHeaderField: "Content-Type")
     request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")


    var response: NSURLResponse? = nil
    var error: NSError? = nil

    let task = NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: imageData, completionHandler: {data, response, error -> Void in

         println(request)
         println(response)
        // println(payload)

    })
    task.resume()

这是我的泽西岛服务:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@Path("/Upload")
public Response fileUpload(
        @FormDataParam("file") InputStream uploadedInputStream,
        @FormDataParam("file") FormDataContentDisposition fileInfo)
        throws IOException
{
     final String FILE_UPLOAD_PATH = "/Users/Luke/Documents/Temp/Uploads";


    Response.Status respStatus = Response.Status.OK;

    if (fileInfo == null)
    {
        respStatus = Response.Status.INTERNAL_SERVER_ERROR;
    }
    else
    {
        final String fileName = fileInfo.getFileName();
        String uploadedFileLocation = FILE_UPLOAD_PATH + File.separator
                + fileName;

        try
        {
            saveToDisc(uploadedInputStream, uploadedFileLocation);
        }
        catch (Exception e)
        {
            respStatus = Response.Status.INTERNAL_SERVER_ERROR;
            e.printStackTrace();
        }
    }

    return Response.status(respStatus).build();
}

我知道该服务可以正常工作,因为我可以通过标准的html页面上传,但是,通过模拟器没有任何内容可以达到其他终点。我显然很新,所以任何指针都会受到赞赏。

以下是模拟器的请求/响应:

    <NSMutableURLRequest: 0x79674830> { URL: http://localhost:8080/rest/service/Upload, headers: {
Accept = "multipart/form-data";
"Content-Type" = "multipart/form-data; boundary=----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";

}}

<NSHTTPURLResponse: 0x7871efa0> { URL: http://localhost:8080/rest/service/Upload } { status code: 406, headers {
"Content-Length" = 0;
Date = "Sun, 28 Sep 2014 07:20:25 GMT";
Server = "Apache-Coyote/1.1";

}}

0 个答案:

没有答案