php上传错误,未定义索引用户文件

时间:2016-11-25 09:17:08

标签: php html

        public class MainActivity extends AppCompatActivity
            implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback {

    SupportMapFragment sMapFragment;
    public GoogleMap mMap;
    private HttpURLConnection urlConnection = null;
    private BufferedReader reader = null;
    private String forecastJsonStr = null;
    private String url = "my_url";

    @Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    sMapFragment = SupportMapFragment.newInstance();


    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    sMapFragment.getMapAsync(this);
    android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
    sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();

}

//Search option

public void onMapSearch(View view) throws IOException {

    //hide button when button is pressed
    InputMethodManager inputManager = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

    //preview the entered address as an Tost in bar
    EditText locationSearch = (EditText) findViewById(R.id.editText);
    String location = locationSearch.getText().toString();

    //this will animate camera and zoom 12.0f
    mMap.animateCamera(CameraUpdateFactory.zoomTo(12.0f));


    //further address search codes
    List<Address> addressList = null;

    //if nothing will be entered in the edit-text will not show a toast rather than crashing of thekha app
    if (locationSearch.getText().toString().equals("")) {
        Toast.makeText(this, "Please enter an Address", Toast.LENGTH_LONG).show();
    } else {

        //process of exception handling and finding location
        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //if address is greater than one then these processes will happen

            if (addressList.size() > 0) {
                Address address = addressList.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                mMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .title(location + " is Here ")
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
                mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                Toast.makeText(this, location + " is here, Zoom In or Zoom Out to make your Thekha Visible ", Toast.LENGTH_LONG)
                        .show(); //popup type to show entered data
            } else {
                //process where entered entry will not gonna find , this will gonna a toast to show popup

                Toast.makeText(this, "Entered Address Not Found", Toast.LENGTH_LONG).show();

            }
        }

    }
}

//Async task

ProgressDialog pd = null;

private class RetriveMarkerTask extends AsyncTask<String, Void, String> {
    private Context context;


    public RetriveMarkerTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        pd = new ProgressDialog(MainActivity.this);
        pd.setTitle("Please wait ...");
        pd.setMessage("Connecting to Loofre Network");
        pd.setCancelable(false);
        pd.show();

    }

    protected String doInBackground(String... markerGetUrl) {
        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            URL url1 = new URL(url);

            // Create the request to OpenWeatherMap, and open the connection
            urlConnection = (HttpURLConnection) url1.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                // Stream was empty.  No point in parsing.
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            forecastJsonStr = "Error, an exception was raised.";
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }
        return forecastJsonStr;

    }

    //on post execution

    protected void onPostExecute(String markers) {


        Log.d("string response", markers);

        Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();

        try {
            JSONArray jsonArray = new JSONArray(markers);
            for (int i = 0; i < jsonArray.length(); i++) {
                //create marker of each place in the json data
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String placeName = jsonObject.getString("name");
                String placeAddress = jsonObject.getString("address");
                double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
                double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
                LatLng loc = new LatLng(latitude, longitude);
                //marker size change code
                int height = 150;
                int width = 150;
                BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
                Bitmap b = bitmapDrawable.getBitmap();
                Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                 mMap.clear();

                mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                        .title(placeName)
                        .snippet(placeAddress)
                        .position(loc));

mMap.addMarker(new MarkerOptions()
                        .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                        .title(placeName)
                        .snippet(placeAddress)
                        .position(new LatLng(gps.getLatitude(),gps.getLongitude())));
     CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(gps.getLatitude(),gps.getLongitude()), 12); 
     map.animateCamera(cameraUpdate);
               }
            pd.dismiss();
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}







@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.call_us) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:+919717001947"));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return true;
        }
        startActivity(intent);

    } else if (id == R.id.about_us) {
        Intent intent = new Intent(this,ScrollingActivity.class);
        this.startActivity(intent);

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

@Override
 public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Connecting Server", Toast.LENGTH_LONG).show();
        mMap = googleMap;
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                    (this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //  int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
        }
        //tool bar and other tool related on map uiSettings
        // mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true); 
    double lat=0;
    double lon=0;
          GPSTracker gps=new GPSTracker(MainActivity.this);

         if(gps.canGetLocation())
          {
             lat=gps.getLatitude();
             lon=gps.getLongitude();
             }

         try {
              LatLng myloc= new LatLng(lat,lon);
        mMap.addMarker(new MarkerOptions().position(myloc).title("Marker in my Locaiton"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(myloc));
            RetriveMarkerTask markerTask = new RetriveMarkerTask(MainActivity.this);
            markerTask.execute(url);
        }catch (Exception e){
            Toast.makeText(this,"Can not fetch data",Toast.LENGTH_LONG).show();
        }


    }

我在使用PHP上传文件时遇到问题。我一直在尝试制作一个上传文件的表单。每次都会出现以下错误。

  

错误:&#34;未定义的索引:用户文件   C:\ wamp64 \ www \ project \ firstfile.php&#34; 。任何解决方案?

4 个答案:

答案 0 :(得分:4)

未定义的索引用户文件,这意味着当页面加载时没有$ _FILES ['imageupload']你需要提交页面以获得该变量

<?php
if(isset($_POST['save'])){
    $path="upload/";
    $name = $_FILES['imageupload']['name'];//Name of the File
    $temp = $_FILES['imageupload']['tmp_name'];
    if(move_uploaded_file($temp, $path . $name)){
        echo "success";
    }else{
        echo "failed";
    }
}
?>
<form method="post" action="" enctype="multipart/form-data">
    <input type="file" name="imageupload">
    <input type="submit" name="save" value="submit">
</form>

答案 1 :(得分:2)

 Please try this  
<?php
        if(isset($_POST['save'])){
            $path = __DIR__ . "/uploads/";
            $img_name = $_FILES['imageupload']['name'];
            $temp_name = $_FILES['imageupload']['tmp_name'];
            if(move_uploaded_file($temp_name, $path . $img_name)){
                echo "uploaded";
            }else{
                echo "failed";
            }
        }
        ?>
        <form method="post" action="" enctype="multipart/form-data">
            <input type="file" name="imageupload">
            <input type="submit" name="save" value="submit">
        </form>

答案 2 :(得分:2)

试试这个,

<form enctype="multipart/form-data" method="post" action="">
    Send this file: <input name="userfile" type="file" /><br />
    <input type="submit" name="btn_submit" value="Send File" />
</form>

<?php
   if(isset($_POST['btn_submit'])){

      $img_name = $_FILES['userfile']['name'];//name of image
      $tmp_name = $_FILES['userfile']['tmp_name'];

  if (move_uploaded_file($tmp_name, "upload/".$img_name)) {
       //your message
    } else {
       //message
    }
?>

答案 3 :(得分:1)

<?php
if(isset($_POST['upload'])){
    $path="uploaddir/";
    $name = $_FILES['userfile']['name'];
    $temp = $_FILES['userfile']['tmp_name'];
    if(move_uploaded_file($temp, $path . $name)){
        echo "success";
    }else{
        echo "failed";
    }
}
?>
<form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
    <input type="file" name="userfile" />
    <input type="submit" name="upload" value="submit" />
</form>