Android Oreo中的图片上传中未找到文件异常

时间:2019-03-11 19:33:19

标签: android httpurlconnection multipart

我正在尝试使用 HttpUrlConnection Multipart 将相机捕获的图像,图库图像和pdf上传到服务器。它在 Android棉花糖设备中工作得很好,但是随后我尝试从 Android Oreo设备上传,它在相机中引发了异常找不到文件异常图片上传,在图库图片中休息,然后pdf上传完美。请帮助

摄像机捕获代码:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = getOutputMediaFile(CAMERA_CAPTURE_IMAGE_REQUEST,getActivity(),moduleType);
                if (file != null) {
                    imageStoragePath = file.getAbsolutePath();
                }
                Uri fileUri = getOutputMediaFileUri(context, file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(intent,CAMERA_CAPTURE_IMAGE_REQUEST);

public File getOutputMediaFile(int type,Context context,String moduleType) {

        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()+File.separator+context.getResources().getString(R.string.app_name)+File.separator+moduleType);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.e(moduleType +"directory", "Oops! Failed create "
                        + moduleType + " directory");
                return null;
            }
        }

        // Preparing media file naming convention
        // adds timestamp
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
                Locale.getDefault()).format(new Date());
        File mediaFile;
        if (type == CAMERA_CAPTURE_IMAGE_REQUEST) {
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + moduleType + timeStamp + "." + "jpeg");
        }else if (type == GALLERY_CAPTURE_IMAGE_REQUEST){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + moduleType + timeStamp + "." + "jpeg");
        }else if (type==PDF_CAPTURE_PICKER_REQUEST){
            mediaFile = new File(mediaStorageDir.getPath() + File.separator
                    + moduleType + timeStamp + "." + "pdf");
        }else {
            return null;
        }

        return mediaFile;
    }

public Uri getOutputMediaFileUri(Context context, File file) {
        return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
    }

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        File selectFile;
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST){
            if (resultCode == RESULT_OK){

                selectFile = new File(imageStoragePath);
                ImageFileBean imageFileBean = new ImageFileBean();
                imageFileBean.setFilePath(selectFile.getAbsolutePath());
                imageFileBean.setFileName(selectFile.getName());
            }
        }
    }

MultipartUtility.class

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

public class MultipartUtilityV2 {
    private HttpURLConnection httpConn;
    private DataOutputStream request;
    private final String boundary =  "*****";
    private final String crlf = "\r\n";
    private final String twoHyphens = "--";

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @throws IOException
     */
    public MultipartUtilityV2(String requestURL)
            throws IOException {

        // creates a unique boundary based on time stamp
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);

        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");
        httpConn.setRequestProperty(
                "Content-Type", "multipart/form-data;boundary=" + this.boundary);

        request =  new DataOutputStream(httpConn.getOutputStream());
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value)throws IOException  {
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf);
        request.writeBytes(this.crlf);
        request.writeBytes(value+ this.crlf);
        request.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" +
                fieldName + "\";filename=\"" +
                fileName + "\"" + this.crlf);
        request.writeBytes(this.crlf);

        byte[] bytes = new byte[0];
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            bytes = Files.readAllBytes(uploadFile.toPath());
        }
        request.write(bytes);
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        String response ="";

        request.writeBytes(this.crlf);
        request.writeBytes(this.twoHyphens + this.boundary +
                this.twoHyphens + this.crlf);

        request.flush();
        request.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream responseStream = new
                    BufferedInputStream(httpConn.getInputStream());

            BufferedReader responseStreamReader =
                    new BufferedReader(new InputStreamReader(responseStream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();

            response = stringBuilder.toString();
            httpConn.disconnect();
        }else if (status == HttpURLConnection.HTTP_INTERNAL_ERROR){
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = null;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            reader.close();
            response = stringBuilder.toString();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

0 个答案:

没有答案