我几天来一直试图解决这个难题。我在swift和c#中的通奸技巧已经赶上了我。
我试图将swift中的图片上传到用c#制作的网络服务中。
但无论我做什么,我最终都会得到同样的错误。
Optional(System.InvalidOperationException: Request format is invalid: multipart/form-data; boundary=Boundary-C59AEB2F-ABB1-4771-8564-D3659108DF7E.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
)
这是我的Swift功能
func uploadImages(){
let url = NSURL(string: "https://www.xxx.xxx/WebService.asmx/UploadVideoFile?VideoFileData=")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data = UIImagePNGRepresentation(UIImage(named: "plainDogFIlledWhite.png")!)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "test.png"
let mimetype = "image/png"
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append("hi\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let response = response, error == nil else {
print("error")
return
}
let dataString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print(dataString)
}
task.resume()
}
我试图让我的服务尽可能简单..
c#service
[WebMethod]
public string UploadVideoFile(byte[] VideoFileData)
{
return "return this";
}