I am trying to upload an image file from an android app using java to an aspnet webapi with no success. I always get a response code of 500. Below is the basic code for preparing the sending of data from my android app. This code works when calling a php script but not when I call a web api controller shown below.
FileInputStream fileInputStream = new FileInputStream(sourceFile);
url = new URL("http://www.myserver.com/webapi/api/fileupload/post/thisfile");
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + sourceFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
Below is the basic web api controller code to do the file upload:
[HttpPost]
[AcceptVerbs("GET", "POST")]
public Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
// return "Unsupported media type";
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = "e:/web/myserver/htdocs/cemetery/pics/";
var provider = new MultipartFormDataStreamProvider(root);
return task;
}
I changed the code above to send back a string and it says that my request does not contain multipart/form-data. Below is my webapiconfig.cs file route for this controller.
config.Routes.MapHttpRoute(
name: "FileUploadApi",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: new { action = "post", name = RouteParameter.Optional }
);
I appreciate any help in determining what is wrong with my code so I can upload a file from an android java app to a webapi controller.