将图像从Android上传到.Net Web API不起作用

时间:2014-12-04 10:51:56

标签: android asp.net

请参阅下面的服务代码:

if (Request.Content.IsMimeMultipartContent())
            {
                try
                {
                    Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
                    {
                        MultipartMemoryStreamProvider provider = task.Result;
                        foreach (HttpContent content in provider.Contents)
                        {
                            Stream stream = content.ReadAsStreamAsync().Result;
                            if (stream == null)
                                lst.Add(new ResponseMsg { status = "Stream empty" });
                            else
                            {
                                Image image = Image.FromStream(stream);
                                var testName = content.Headers.ContentDisposition.Name;
                                String fileName = content.Headers.ContentDisposition.FileName;
                                String fullPath = Path.Combine(path, "sample_" + DateTime.Now.Hour.ToString() + "_" + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Second.ToString() + ".jpg");
                                image.Save(fullPath);
                                lst.Add(new ResponseMsg { status = "success" });
                            }
                        }
                    });
                    lst.Add(new ResponseMsg { status = "Request content empty" });
                }
                catch (Exception e)
                {
                    lst.Add(new ResponseMsg { status = e.Message });
                }

            }
            else
            {
                lst.Add(new ResponseMsg { status = "This request is not properly formatted" }); ;
            }

而且,这是我的安卓代码:

try {
                InputStream result = null;
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(
                        "/storage/sdcard0/DCIM/Camera/1417504088698.jpg");              
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                URL url = new URL("URL");

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy

                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Cache-Control", "no-cache");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                //conn.setRequestProperty("uploaded_file", "1417504088698.jpg");
                //conn.setRequestProperty("Image", text);

                dos = new DataOutputStream(conn.getOutputStream());
                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"\";filename=\""
                        + "1417504088698.jpg" + "\"" + lineEnd);

                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    //dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }
                dos.write(buffer);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                dos.flush();
                dos.close();

                result = (InputStream) conn.getContent();

                if (result != null) {
                    Reader reader = new InputStreamReader(result);
                    Gson gson = new Gson();
                    if (reader != null) {
                        rMsg = gson.fromJson(reader, ResponseMsg[].class);
                    }
                }

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

执行时我正在获取statusCode:OK,并显示消息:“请求内容为空”。该文件未保存在服务器中。我该如何解决这个问题。请帮忙。

0 个答案:

没有答案