图片上传 returns 未找到文件异常

image uploading returns a File not found exception

我正在尝试将图像从 Android 客户端上传到 .net 网站 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
}

实际发生的事情是 - 不知何故,图像没有从客户端正确发送。在这种情况下得到您的帮助会很棒。谢谢

我找到了解决办法。 Android HttpUrlConnection 对于文件上传之类的东西有点限制。它有一个特定的格式——如果违反它就不会工作。格式为

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

Image data 
--xxxxxxxxxx--

这里的'xxxxxx'部分就是我们所说的boundary。 '--' 是两个连字符。并且 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