图片上传返回File not found异常

时间:2018-08-12 10:48:17

标签: android asp.net-web-api image-uploading

我正在尝试将图像从Android客户端上传到.net Web API。我无法弄清楚客户端代码出了什么问题。

客户代码

@Override
protected String doInBackground(String... strings) {
    try {
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1024 * 1024;
        File file = new File(imagePath);

        URL url = new URL(strings[0]);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection", "Keep-Alive");
        //connection.setRequestProperty("ENCTYPE", "multipart/form-data");
        connection.setRequestProperty("Authorization", "bearer "+ LoginActivity.token);
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

        DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());

        Log.d("file path", file.getPath() );

        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        //outputStream.writeBytes(lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"ProfilePic\"; filename=\""+ file.getAbsolutePath() + "\"" + lineEnd);
        outputStream.writeBytes("Content-Type: image/png" + lineEnd);

        FileInputStream fileInputStream;
        fileInputStream = new FileInputStream(file.getAbsoluteFile());
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        // Read file
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            try{
                outputStream.write(buffer, 0, bufferSize);
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                Log.d("Exception occured", "Out of memory");
                return "out of memory";
            }
            bytesAvailable = fileInputStream.available();
            Log.d("output stream", outputStream+"");
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        outputStream.writeBytes(lineEnd);
        outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        Log.d("Response image upload", connection.getResponseCode()+"");

        /*** output printing ***/
        BufferedReader _reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = "";
        StringBuilder response = new StringBuilder();

        while( (line = _reader.readLine()) != null ) {
            response.append(line);
        }

        String data = response.toString();

        Log.d("Output data", data);
        /****/

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

服务器代码

[HttpPost]
public IHttpActionResult SaveImage()
{
 var httpRequest = HttpContext.Current.Request;
 HttpPostedFile file = httpRequest.Files["ProfilePic"];

 if (file == null)
   throw new EmptyObjectException(ErrorMessageTypes.EmptyObject, jobSeekerId);

 // saving the image
}

实际发生的是-客户端无法正确发送图像。在这种情况下获得您的帮助将是很棒的。谢谢

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 Android HttpUrlConnection在文件上传方面有点受限制。它具有特定的格式-如果违反该格式将不起作用。格式是

--xxxxxxxxxx
Content-Disposition: form-data; name="filetoupload"; filename="helloworld.png"
Content-Type: image/png

Image data 
--xxxxxxxxxx--

此处“ xxxxxx”部分是我们称为边界的部分。 “-”是两个连字符。并且lineEnd必须以正确的数量放置在正确的位置。所以在我的代码中应该是

outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"ProfilePic\"; filename=\""+ file.getPath() + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: image/png" + lineEnd);
outputStream.writeBytes(lineEnd);

FileInputStream fileInputStream;
fileInputStream = new FileInputStream(file.getPath());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
    try{
        outputStream.write(buffer, 0, bufferSize);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        Log.d("Exception occured", "Out of memory");
        return "out of memory";
    }
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

我感谢this blog