Yes, you can file for a residency permit in Spain both from your country (Spanish Consulate) and from Spain. You need to check out the visa options for your case.